Defining Object Constructors






Defining Object Constructors

Problem

You want to define a method that is called when an object is instantiated. For example, you want to automatically load information from a database into an object upon creation.

Solution

Define a method named __construct( ):

class user {
    function __construct($username, $password) {
        ...
    }
}

Discussion

The method named __construct( ) (that's two underscores before the word construct) acts as a constructor, as shown in Figure.

Defining an object constructor

class user {
  public $username;

  function __construct($username, $password) {
     if ($this->validate_user($username, $password)) {
       $this->username = $username;
     }
  }
}

$user = new user('Grif', 'Mistoffelees'); // using built-in constructor

In PHP 4, constructors had the same name as the class, as shown in Figure.

Defining object constructors in PHP 4

class user {
  function user($username, $password) {
  ...
  }
}

For backward compatibilty, if PHP 5 does not find a method named __construct( ), but does find one with the same name as the class (the PHP 4 constructor naming convention), it will use that method as the class constructor.

Having a standard name for all constructors, such as what PHP 5 implements, makes it easier to call your parent's constructor (because you don't need to know the name of the parent class) and also doesn't require you to modify the constructor if you rename your class.

See Also

Recipe 7.14 for more on calling parent constructors; documentation on object constructors at http://www.php.net/oop.constructor.



 Python   SQL   Java   php   Perl 
 game development   web development   internet   *nix   graphics   hardware 
 telecommunications   C++ 
 Flash   Active Directory   Windows