HomePHP Page 4 - The Destruct Magic Function in PHP 5
Creating a persistable object with the destruct method - PHP
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.
Undeniably, the best way to grasp how the previous “__destruct()” method is called by the PHP interpreter is by means of a concrete example. Thus, with that idea in mind, below I coded a simple script that spawns an instance of the “User” class, and then adds some properties to it.
The aforementioned script looks as follows:
// example on implementing the '__destruct()' magic method
$user = new User();
$user->fname = 'Alejandro';
$user->lname = 'Gervasio';
$user->email = 'firstname.lastname@example.org';
Admittedly, the above script looks pretty boring, aside from showing how to overload some properties of the “User” class. However, things are a bit tricky in this case, since right before the script finishes its execution (and the user object gets destroyed), the “__destruct()” method will be invoked, therefore storing the object on a session variable.
Of course, it’s also feasible to make the method save the object to a database table, or even to a flat file. Certainly, possibilities are numerous and very interesting to try out.
And finally, feel free to edit all of the code samples included in this tutorial, so you can arm yourself with a better background in using destructors in PHP 5.
Over this sixth episode of the series, I covered another magic method that comes packaged with PHP 5, that is the popular “__destruct(),” also known as a destructor. As was demonstrated previously, destructors 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.
Now, speaking specifically of the topics that will be discussed in the last tutorial, I must admit that there’s still a magic function that we haven't explored so far, which is used commonly within PHP programs to load classes automatically.
Yes, you guessed right -- I’m talking about the “__autoload()” function. If you want to learn how to work with it, then don’t miss the final chapter of this series!