Recipe 7.2. Defining Object Constructors


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

7.2.2. Solution

Define a method named __construct( ):

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

7.2.3. Discussion

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

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

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.

7.2.4. See Also

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




PHP Cookbook, 2nd Edition
PHP Cookbook: Solutions and Examples for PHP Programmers
ISBN: 0596101015
EAN: 2147483647
Year: 2006
Pages: 445

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net