PHP 5: The constructor method

The introduction of a method called __construct() means that function User() no longer need be the default method name for instantiating an instance of the User class. This is especially useful in the case where you are using subclasses, or if the name of the class changes during development. E.g. In the example above, the constructor for User is called User() and the constructor for AdminUser is called AdminUser().

class User
{
 function __construct()
 {
 }
}
class AdminUser extends User
{
 //No constructor in here, so we’ll
 //use the parent’s code
}

Alternatively, the AdminUser constructor may use the majority of code from its parent but may also add to it. The parent’s constructor may then be called from within the child class.

class User
{
 function __construct()
 {
 }
}

class AdminUser extends User
{
 function __construct()
 {
  $isAdmin=true;
  //Call the parent’s constructor now
  parent::__construct();
 }
}

Next section: Public, private, protected