7.2. 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 when it’s created.

Solution

Define a method with the same name as the class:

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

Discussion

If a function has the same name as its class, it acts as a constructor:

class user {
    var $username;

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

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

PHP hasn’t always had support for constructors. So people made pseudo-constructors by adopting a naming convention and calling that function after creation:

class user {
    ...

    init($username, $password) { ... }
}

$user = new user();
$user->init($username, $password);

If you see this, it’s usually a result of legacy code.

However, having a standard name for all constructors 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 name. With Zend Engine 2, the naming conventions of constructors have been modified, and the new constructor name is _ _construct( ). However, for backwards compatibility, if this method isn’t found, PHP tries to call a constructor with the same name as the class.

See Also

Recipe 7.8 for more ...

Get PHP Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.