Welcome to the sixth part of a seven-part series that shows you how to use the magic functions that come with PHP 5. In this article, I cover the “__destruct()” method, also known as a destructor. They can be really useful for performing all sorts of clean-up tasks, or for creating objects that are capable of maintaining their state across several HTTP requests.
To be frank, learning how to implement and use the magic functions that come included with PHP 5 isn’t as hard as it may seem at first glance. The entire process requires knowing which event triggers a particular function, and then giving that function a concrete definition in accordance with the specific needs of the application being developed.
So, if you’re a PHP programmer who is searching for a comprehensive guide that introduces you gently to using the most important magic methods provided by PHP 5, then this group of articles may be the material that you need to start reading right away!
If you already went through all of the articles that precede this one, then it’s probable that by now you have a solid background in working with the most relevant PHP 5 magic functions. This includes, among others, the handy trio comprised of the “__set()”, “__get()” and “__call()” methods; the “__sleep()” and “__wakeup()” functions; and the “__clone()” method, which was explored in depth in the last tutorial of this series.
However, it’s fair to say that the aforementioned functions aren’t the only ones that you can use within your classes. There are a few others that can be really useful for performing relatively complex tasks with a minimal amount of code. That’s exactly the case with the “__destruct()” method, which will be called automatically by the PHP engine before destroying an instance of a particular class at the end of a script.
Indeed, implementing destructors is itself a huge subject that is out of the scope of this series for now. Yet, during this tutorial I’m going to discuss how to add a destructor to the sample “User” class that you saw in previous articles, so you can learn how to use it for constructing simple persistable objects.
Now, it’s time to get rid of the dull theory and start discovering how to use the “__destruct()” PHP 5 magic method. Let’s jump in!