PHP Cookbook: Solutions and Examples for PHP Programmers
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
In PHP 4, constructors had the same name as the class, as shown in Example 7-5. Defining object constructors in PHP 4
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. |
Категории