|
Constructors and DestructorsConstructor
void __construct
([ mixed
$args
[, $...
]] )PHP 5 allows developers to declare constructor methods for classes. Classes which have a constructor method call this method on each newly-created object, so it is suitable for any initialization that the object may need before it is used.
Example #1 using new unified constructors
<?php For backwards compatibility, if PHP 5 cannot find a __construct() function for a given class, and the class did not inherit one from a parent class, it will search for the old-style constructor function, by the name of the class. Effectively, it means that the only case that would have compatibility issues is if the class had a method named __construct() which was used for different semantics.
Unlike with other methods, PHP will not generate an
As of PHP 5.3.3, methods with the same name as the last element of a namespaced class name will no longer be treated as constructor. This change doesn't affect non-namespaced classes. Example #2 Constructors in namespaced classes
<?php Destructor
void __destruct
( void
)
PHP 5 introduces a destructor concept similar to that of other object-oriented languages, such as C++. The destructor method will be called as soon as there are no other references to a particular object, or in any order during the shutdown sequence. Example #3 Destructor Example
<?php Like constructors, parent destructors will not be called implicitly by the engine. In order to run a parent destructor, one would have to explicitly call parent::__destruct in the destructor body. Also like constructors, a child class may inherit the parent's destructor if it does not implement one itself. The destructor will be called even if script execution is stopped using exit. Calling exit in a destructor will prevent the remaining shutdown routines from executing.
|