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!
Want to learn PHP 7?
Hacking with PHP has been fully updated for PHP 7, and is now available as a downloadable PDF. Get over 1200 pages of hands-on PHP learning today!
If this was helpful, please take a moment to tell others about Hacking with PHP by tweeting about it!
Next chapter: Deleting objects >>
Previous chapter: Parent constructors
Jump to:
Home: Table of Contents
Copyright ©2015 Paul Hudson. Follow me: @twostraws.