Setting default values with a constructor method



When you create an instance of a class, PHP automatically looks for the class’s constructor method (or constructor). As the name indicates, a constructor builds the object, applying default values and assigning to properties values passed to the class when an object is instantiated.

In many languages, the constructor is a method that shares the same name as the class. This is how PHP objects were built in PHP 3 and 4. However, since PHP 5, the constructor for all classes is called __construct() (with two leading underscores). Using a constructor is optional, but most classes do use one.

The constructor works like a setter method, so any values passed to it as arguments can be assigned to properties by using $this to refer to the current object like this:

public function __construct($value)
{
$this->_property = $value;
}