Skip to Content
PHP Cookbook
book

PHP Cookbook

by David Sklar, Adam Trachtenberg
November 2002
Intermediate to advanced
640 pages
16h 33m
English
O'Reilly Media, Inc.
Content preview from PHP Cookbook

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 ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

PHP Cookbook

PHP Cookbook

Eric A. Mann
PHP Cookbook, 2nd Edition

PHP Cookbook, 2nd Edition

Adam Trachtenberg, David Sklar
PHP Cookbook, 3rd Edition

PHP Cookbook, 3rd Edition

David Sklar, Adam Trachtenberg
Programming PHP

Programming PHP

Rasmus Lerdorf, Kevin Tatroe

Publisher Resources

ISBN: 1565926811Supplemental ContentCatalog PageErrata