Recipe 7.3 Defining Object Constructors
7.3.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 when
it's created.
7.3.2 Solution
Define a method with the same name as the class:
class user {
function user($username, $password) {
...
}
}
7.3.3 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.
7.3.4 See Also
Recipe 7.8 for more on calling parent
constructors; documentation on object constructors at
http://www.php.net/oop.constructor.
|