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

Advertisements
This entry was posted in PHP, Programming. Bookmark the permalink.

One Response to PHP 5: The constructor method

  1. masternico says:

    Actually, the son object doesn't automaticaly call the parent's contructor. So it's a good thinking to always use the second exemple in order to be sure the parent object is corectly instanciated…

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s