PHP Classes and Objects
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: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
For backward compatibilty with PHP 4, 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 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.
No comments:
Post a Comment