Home / Articles / Programming languages / Scripting languages / PHP / Classes and objects in PHP: constructors

Classes and objects in PHP: constructors

Classes and objects in PHP: constructors
 
Classes and objects in PHP: constructors
  • Currently 4 out of 5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
Rating: 4/5 (1 votes cast)

Thank you for rating!

You have already rated this page, you can only rate it once!

Your rating has been changed, thanks for rating!

Log in or create a user account to rate this page.


Quite often, when creating an object it is required to set values to some properties. Fortunately, the developers of OOP took this into account and implemented it in the concept of constructor. The constructor is a method that sets the values to some of properties (also it may call other methods.) The constructor is called automatically when a new object is created. To make this possible, the name of the constructor method must be the same as the name of the class in which it is contained. An example of a constructor:

class Design {
  var $bgcolor;
  function Design($color) {
    $this->bgcolor = $color;
  }
}

// Call the constructor Design
$page = new Design('gray');

Previously, object creation and property initialization had to be performed separately. Constructors can perform these tasks in one step.

An interesting fact: different constructors are called depending on the number of passed parameters. In this example, Design class objects can be created in two ways. First, you can call the constructor, which only creates an object, but does not initialize its properties:

$page = new Design;

Second, an object can be created using the constructor defined in class - in this case, you create an object of Design class and assign a value to its property bgcolor:

$page = new Design('gray');

 

Read also

What is PHP?

What is PHP?

Classes and objects in PHP

Classes and objects in PHP

How to access classes and objects in PHP

How to access classes and objects in PHP

Post comment

basicuse.net
html5_css
106160485398655174790

Quick navigation

General navigation