Constructors
PHP 5 introduces the concept of the
unified constructor and, along with it, a new destructor for objects. The
constructor and destructor are special class methods that are called, as their
names suggest, on object creation and destru ction, respectively. Constructors
are useful for initializing an object’s properties, or for performing start-up
procedures, such as, for example, connecting to a database, or opening a remote
file.
The concept of the constructor is,
of course, not new to PHP 5. In PHP 4, it was possible to define a class method
whose name was the same as the class itself; PHP would then consider this
method to be the class’ constructor and call it whenever a new instance of the
class was created. This approach had several drawbacks—for example, if you
decided to rename your class, you would also have to rename your constructor.
To avoid these problems, PHP 5 now
uses the magic __construct() method as the constructor for any class regardless
of the class’ name. This greatly simplify things, and provides you with a
standard mechanism to recognize and call constructors in a consistent manner:
class foo {
function __construct()
{
echo __METHOD__;
}
function foo()
{
// PHP 4 style constructor
}
}
new foo();
This example will display foo::__construct
(the__METHOD__constant is replaced at compilation time with the name of the
current class method). Note that, if the __
construct() method is not found, PHP
will look for the old PHP 4-style constructor (foo) and call that instead.
0 Comment to " PHP Constructors "
Post a Comment