Constructors and Destructors
Constructor
void__construct
mixedargs
...
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.
Parent constructors are not called implicitly if the child class defines
a constructor. In order to run a parent constructor, a call to
parent::__construct within the child constructor is
required.
using new unified constructors
]]>
For backwards compatibility, if PHP 5 cannot find a
__construct function for a given 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.
Destructor
void__destruct
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 all references to a particular object are removed or when
the object is explicitly destroyed or in any order in shutdown sequence.
Destructor Example
name = "MyDestructableClass";
}
function __destruct() {
print "Destroying " . $this->name . "\n";
}
}
$obj = new MyDestructableClass();
?>
]]>
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.
Destructors called during the script shutdown have HTTP headers already
sent. The working directory in the script shutdown phase can be different
with some SAPIs (e.g. Apache).
Attempting to throw an exception from a destructor (called in the time of
script termination) causes a fatal error.