Understanding Destructors in PHP 5

Despite the scary-sounding name, destructors aren’t evil. Indeed, their use is often necessary to help keep your applications running properly. This article, the first part of a five-part series, introduces you to destructors and their use with PHP 5 programs.

Generally, people tend to associate the term “destructor” with something that will be used with bad intentions. And to be frank, this attitude has some common sense behind it. After all, if there is such a thing with that scary name, well, it must be evil, and capable of destroying other stuff also.

Fortunately, in the terrain of software development, things aren’t really so drastic really (excepting when your boss isn’t in the mood for jokes). The word "destructor" relates to certain methods or functions of a determined programming language that are responsible for destroying data that, in the context of that particular language, shouldn’t exist any longer.

Speaking more specifically, PHP has a certain number of native routines that are clear examples of “destructive” behaviors that can be healthy during the execution of a specific application. To cite a paradigmatic example, consider its garbage recollection mechanism. It is charged with removing expired session data, useless database links, and so forth. Undoubtedly, under determined conditions, functions or methods that destroy certain data are not only useful, but completely mandatory.

However, aside from the intrinsic destruction mechanisms provided by PHP, there’s another one that was introduced within the improved object model of PHP 5, which actually will be subject of this article series. Obviously, if you read this tutorial’s title, then you’ll possibly know what I’m talking about: the so-called destructor methods.

In case you didn’t know, PHP 5 provides programmers with the capacity for defining inside a given class, a special method called “__destruct()”, which as its name suggests, will be automatically invoked when an object instantiated from that class no longer exists in the context of a certain application.

In the same way that a constructor is executed automatically when a new object is created in PHP, their “__destruct()” counterpart will be called up when the object in question is removed from the web server’s memory. Continuing with the similarities between constructors and destructors, destructors also have a non-default implementation, which gives programmers the ability to define them according to their specific needs.

Now that I provided you with a brief introduction to what destructors are in PHP 5, in this series of articles I’m going to show you the basics of how to work with them. The corresponding theory will be complemented with illustrative hands-on examples that you’ll be able to test and study easily, so you can start using them with your own PHP 5-driven applications.

At this point, it’s time to get rid of the preliminaries and begin learning how to use destructors with PHP 5, so let’s move on and start this instructive journey right now!

{mospagebreak title=Building a Sample}

Building a sample PHP 5 class that doesn’t use a destructor

An adequate point to start demonstrating how to declare and use class destructors is to step on the opposite side of the river (yes, my metaphoric skills really amaze me all the time). By this I mean building a sample class that lacks a destructor method, as you’ve done probably hundreds of times when using classes in PHP 4.

Having said that, suppose that a specific PHP application requires working with objects that represent a determined range of users. Based upon this fictional scenario, I’m going to define a generic class, called “User,” which is convenient for storing some common properties of these hypothetical users, such as their first and last names, and their email addresses as well.

Basically, this class has the following signature:


// define ‘User’ class

class User{

private $firstName;

private $lastName;

private $email;

public function __construct($firstName,$lastName,$email){

if(!$firstName||strlen($firstName)>32){

throw new Exception(‘Invalid First Name parameter!’);

}

if(!$lastName||strlen($lastName)>32){

throw new Exception(‘Invalid Last Name parameter!’);

}

if(!$email||!preg_match("/^.+@.+..+$/",$email)){

throw new Exception(‘Invalid Email parameter!’);

}

$this->firstName=$firstName;

$this->lastName=$lastName;

$this->email=$email;

}

// get user’s first name

public function getFirstName(){

return $this->firstName;

}

// get user’s last name

public function getLastName(){

return $this->lastName;

}

// get user’s email

public function getEmail(){

return $this->email;

}

// get all user data

public function getAll(){

return ‘First Name: ‘.$this->firstName.’ Last Name: ‘.$this->lastName.’ Email Address: ‘.$this->email;

}

}

As shown above, the “User” class that I just defined exposes some basic properties, along with a group of accessing methods tasked with returning the values assigned to the properties to client code. So far, understanding how this class works isn’t going to make you lose your hair, right?

After defining that simple “User” class, it’s time to see how it works in a concrete case, so let me show you a basic script that first creates a new user object, then assigns some trivial values to the pertinent properties, and finally outputs these values to the browser.

The signature of the script looks like this:

try{

// create new instance of ‘User’ class

$user=new User(‘John’,’Doe’,’john@domain.com’);

// display separately user data

echo ‘First Name: ‘.$user->getFirstName().'<br />';

echo ‘Last Name: ‘.$user->getLastName().'<br />';

echo ‘Email: ‘.$user->getEmail().'<br />';

// display all user information

echo ‘Complete user information: ‘.$user->getAll();

 

/* displays the following

 

First Name: John

Last Name: Doe

Email: john@domain.com

Complete user information: First Name: John Last Name: Doe Email Address: john@domain.com

 

*/

 

}

catch(Exception $e){

echo $e->getMessage();

exit();

}


Until now, the class performs fairly well. As you can see in the previous example, a user object is created and its properties are accessed via the corresponding methods. What else could you ask for? Well, not so fast. Suppose for an instant that you need to serialize the entire object for debugging purposes, right before the script finishes its execution.

This could be quickly done by defining an additional class method that performs this serialization process. However, in doing so, the method should be called explicitly, right? Here’s where class destructors come in, since in PHP 5 it’s possible to implement concretely a “__destruct()” method, which will be automatically called by the interpreter (not direct invocation is needed) before an object is destroyed.

In this particular case, the above user object could simply use a destructor to serialize itself, prior to being removed from the web server’s memory. Sounds quite useful, doesn’t it? All right, now that you’ve seen how to work with a generic user class that doesn’t declare a “__destruct()” method as part of its API, it’s time to learn how to implement a basic destructor within the aforementioned class.

As you might have guessed, I’ll be analyzing destructors in the upcoming section, so go ahead and read it. It’s only one click away.

{mospagebreak title=Introducing Class Destructors}

Calling a concrete method before destroying an object: introducing class destructors

In the previous section, you learned how to build a simple class that didn’t define a destructor method inside its API, which could be necessary under certain conditions. Of course, I’m not saying that from this point onward each class you work with must declare a destructor, because this would be pointless.

However, let me show you a modified version of the “User” class that you learned before. This time I will include a very primitive “__destruct()” method. Please study the brand new definition of the class in question:


// basic example on using a ‘__destruct()’ method 


// define ‘User’ class

class User{

private $firstName;

private $lastName;

private $email;

public function __construct($firstName,$lastName,$email){

if(!$firstName||strlen($firstName)>32){

throw new Exception(‘Invalid First Name parameter!’);

}

if(!$lastName||strlen($lastName)>32){

throw new Exception(‘Invalid Last Name parameter!’);

}

if(!$email||!preg_match("/^.+@.+..+$/",$email)){

throw new Exception(‘Invalid Email parameter!’);

}

$this->firstName=$firstName;

$this->lastName=$lastName;

$this->email=$email;

}

// get user’s first name

public function getFirstName(){

return $this->firstName;

}

// get user’s last name

public function getLastName(){

return $this->lastName;

}

// get user’s email

public function getEmail(){

return $this->email;

}

// get all user data

public function getAll(){

return ‘First Name: ‘.$this->firstName.’ Last Name: ‘.$this->lastName.’ Email Address: ‘.$this->email;

}

// implement a __destruct()’ method

public function __destruct(){

echo ‘<h2>Destroying user now…<h2>';

}

}


As you can realize, defining a destructor for a determined PHP 5 class isn’t rocket science; the whole process is reduced to defining a “__destruct()” method, and then implementing it correctly. In this case, my destructor is actually very primitive and will display the message “Destroying user now…” before the corresponding object is destroyed.

So far, so good. At this point, you’ve grasped the basics of defining a destructor within the previous “User” class, something that hopefully has caught your attention. Therefore, I’m going to create a test example, aimed at demonstrating the limited functionality of the destructor we just created.

To see how this brand new example will be developed, please visit the next section and keep reading.

{mospagebreak title=Testing the Previous User Class}

Seeing a destructor method in action: testing the previous user class

If you’re anything like me, you may want to see how the prior “User” class functions after implementing its corresponding destructor. Well, I have to admit that I’m feeling quite curious too. Below I coded another sample script, which demonstrates how the destructor is called when the script finishes its execution, and consequently any object spawned from the previous user class is also destroyed.

Now that I have explained that, please study the following code sample:


try{

// create new instance of ‘User’ class

$user=new User(‘John’,’Doe’,’john@domain.com’);

// display separately user data

echo ‘First Name: ‘.$user->getFirstName().'<br />';

echo ‘Last Name: ‘.$user->getLastName().'<br />';

echo ‘Email: ‘.$user->getEmail().'<br />';

// display all user information

echo ‘Complete user information: ‘.$user->getAll();

}

catch(Exception $e){

echo $e->getMessage();

exit();

}


Frankly speaking, the above example looks identical to the one that you saw in the prior section. However, this first impression is a bit tricky; if you test this example on your system, you’ll see that it outputs the following on the browser:


First Name: John

Last Name: Doe

Email: john@domain.com

Complete user information: First Name: John Last Name: Doe Email Address: john@domain.com

Destroying user now…

Hey, what’s that last phrase at the end of the output? Yes, you guessed right! Once a user object is created and used in a simple manner, the script finishes running…but before this happens, the pertinent “__destruct()” method is called automatically, in this way displaying the message “Destroying user now…”

At this moment, you’ll have to agree with me that working with destructors in PHP 5 is a very simple process. Naturally, my implementation of the “__destruct()” method in the previous example is primitive, but I believe that this should be clear enough for you to grasp the logic that stands behind using destructors.

My final recommendation is simply that you play with this sample user class and test different implementations for its destructor to see what happens in each case.

Final thoughts

In this initial article of the series I walked you through learning the basic concepts that surround the use of class destructors with PHP 5. As you saw from the sample classes that I built previously, declaring and implementing these special class methods are actually no-brainer processes that can be grasped quickly, even if you’re only starting to work with classes and objects.

In the next part of the series, things will become far more interesting and complex. I’m going to teach you how to work with multiple classes that implement obviously different destructors.

Now that you’ve been warned, you simply can’t miss the next article!

[gp-comments width="770" linklove="off" ]
antalya escort bayan antalya escort bayan