6.10.2 DestructorsThis is NOT the latest copy of this book; click here for the latest version.
Constructors are very useful, as I am sure you will agree, but there is more: PHP also allows you to define class destructors - a function to be called when an object is deleted. PHP calls destructors as soon as objects are no longer available, and the destructor function, __destruct(), takes no parameters.
Take a look at the following code:
public function __destruct() {
print "{$this->Name} is no more...\n";
}
If you add that function into the poodle class, all Poodles created will have that function called before being destroyed. Add that into the same script as the constructor we just defined for poodles, and run it again - here's what it outputs:
Creating Poppy
Creating a poodle
My name is Poppy. If you find me, please call 555-1234
Poppy is no more...
Like constructors, destructors are only called once - you need to use parent::__destruct(). The key difference is that you should call parent::__destruct() after the local code for the destruction so that you are not destroying variables before using it, for example:
public function __destruct() {
print "{$this->Name} is no more...\n";
parent::__destruct();
}
Destructors are useful to free up resources once you are done with them, but they are also good for keeping track of your objects - you can perform any actions you want in destructors, so take advantage of them!
Author's Note: Destructors were not possible in PHP 4, so do not be surprised if you find old bits of code around that try to emulate destructors in odd ways. One of the most popular ways of handling destructors before PHP 5 was to keep an array of the objects that were created, and register a shutdown function to iterate through this array and clean up the objects by hand.
|
Want to see this stuff in print? PHP in a Nutshell takes the core topics covered here, adds in thousands of edits from the editorial team and myself, and combines them to make an unbeatable reference for PHP programmers at all levels.
My latest book has hundreds more tips on how to use PHP, Apache, and MySQL, plus Perl, Python, shell scripts, performance tuning, and more!
|