The Destruct Magic Function in PHP 5

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!

{mospagebreak title=Review: the clone magic function}  

In case you still haven’t had the opportunity to read the last installment of the series, where I explained how to trigger the “__clone()” method when cloning an instance of the sample “User” class coded previously, below I included the source class of this class, along with a rudimentary example that shows how to use it. 

Here’s the class that implements the “__clone()” method:

 

class User

{

// constructor (not implemented)

public function _construct(){}

 

// set undeclared property in a restrictive way

public function __set($property, $value)

{

if (in_array($property, array(‘fname’, ‘lname’, ‘email’)) === TRUE)

{

$this->$property = $value;

}

}

 

// get undeclared property

public function __get($property)

{

if (isset($this->$property))

{

return $this->$property;

}

}

 

// single point to fetch user data

public function __call($method, $args)

{

if ($method === ‘fetch’ AND empty($args) === FALSE)

{

return $this->$args[0];

}

}

 

// implement __clone( method

public function __clone()

{

echo ‘Cloning user object.';

}

}

 

From the above code sample, it’s clear to see how easy it is to give a concrete implementation to the “__clone()” method. In this particular case, the method has been coded to display a message on screen when a user object is being cloned, but it’s perfectly possible to define it for performing more useful tasks. 

Now that you hopefully recalled how to include this magic method within a specific class, below there’s an example that demonstrates how things look behind the scenes when an instance of the “User” class is cloned via the “clone” keyword. 

Take a look at the following script:

 

$user = new User();

$user->fname = ‘Alejandro';

$user->lname = ‘Gervasio';

$user->email = ‘alejandro@mydomain.com';

// display user data

echo ‘First Name : ‘ . $user->fetch(‘fname’) . ‘ Last Name : ‘ . $user->fetch(‘lname’) . ‘ Email : ‘ . $user->fetch(‘email’);

/*

displays the following

First Name : Alejandro Last Name : Gervasio Email : alejandro@mydomain.com

*/

 

// clone user object

$newuser = clone $user;

/*

displays the following

Cloning user object.

*/

 

See how simple it is to put the “__clone()” magic method into action? I guess you do. In this case, when the “clone” keyword is utilized for cloning a user object, the method displays an indicative message on the browser. It’s that easy, actually. 

So far, so good. At this stage, you’ve surely learned how to implement the “__clone()” magic function within a class. So, it’s time to explore another handy method included with PHP 5. Yes, as you might have guessed, I’m talking about the “__destruct()” method, which unlike its counterpart “__construct()” is triggered before destroying a specified object. 

As I explained earlier, destructors can be used for performing all sorts of clever tasks, and taking this capability into account, in the next section I’m going to reuse the previous “User” class by adding a destructor to it, so you can learn the full details of this process. 

That being said, please click on the link that appears below and read the following segment. I’ll be there, waiting for you.

{mospagebreak title=Working with destructors in PHP 5} 

As I stated in the previous segment, it’s possible to accomplish interesting and useful things with a destructor. In this case, I’m going to use it within the already familiar “User” class to create an object that will save itself to a session variable before being destroyed. 

How will this be achieved? Well, take a look at the enhanced definition of the “User” class, which now implements the “__destruct()” method. Here it is:

 

// define ‘User’ class (implements the __destruct() magic method)

class User

{

// constructor (not implemented)

public function _construct(){}

 

// set undeclared property in a restrictive way

public function __set($property, $value)

{

if (in_array($property, array(‘fname’, ‘lname’, ‘email’)) === TRUE)

{

$this->$property = $value;

}

}

 

// get declared property

public function __get($property)

{

if (isset($this->$property))

{

return $this->$property;

}

}

 

// single point to fetch user data

public function __call($method, $args)

{

if ($method === ‘fetch’ AND empty($args) === FALSE)

{

return $this->$args[0];

}

}

public function __destruct()

{

session_start();

$_SESSION['user'] = serialize($this);

}

}

 

As shown above, the implementation of the “__destruct()” method is very easy to follow. All it does is start or resume a new session, and then save an instance of the “User” class to a session variable. Period. 

Logically, nothing spectacular is happening here, except for the fact that all of these tasks will be performed before the instance of the user class gets destroyed. In this manner we’re building an object that has the ability to maintain its state across different HTTP requests, by using only the PHP built-in session mechanism. 

Even though the definition of the “__destruct()” method is indeed self-explanatory, an example is in order her to understand how it works. Therefore, in the last section of this tutorial I’m going to set up such an example, so you can see how the destructor does its thing. 

To learn how this wrapping example will be created, click on the link shown below and keep reading. We’re almost done exploring destructors!

 

{mospagebreak title=Creating a persistable object with the destruct method} 

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 = ‘alejandro@mydomain.com';

 

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.

Final thoughts  

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!

[gp-comments width="770" linklove="off" ]

chat