Implementing Destructors with Multiple Objects in PHP 5

Welcome to the second installment of the series “Understanding Destructors in PHP 5.” Whether you’re a PHP programmer who’s making their first steps in the area of professional PHP development, or an experienced developer with a solid background in object-based PHP programming, this article series can provide you with an approachable guide for using destructors in PHP 5-controlled development environments.

If you’re starting to get familiar with the numerous features incorporated into the improved object model of PHP 5, then you may have already heard about class destructors. But what are they? Simply put, a destructor is a method defined by a given class that will be automatically called by the PHP interpreter before destroying any instance of that particular class.

Indeed, they can be quite useful for tracking the status of objects during the execution of different scripts. Therefore, if you’re interested in learning how to work with destructors within your own PHP 5 classes, then this group of articles might be what you’re looking for.

Now that I’ve introduced you to the main subject of this series, I’d like to spend a few moments rehashing the items we discussed in the last article regarding the basic utilization of destructors with PHP 5. As you’ll probably recall, during that particular tutorial I walked you through both the theoretical and practical concepts concerning the definition and implementation of a simple destructor method within a sample class.

In that specific case, I utilized a trivial “User” object to show how its corresponding destructor was called right before destroying the object in question. In this way I illustrated how the functionality of destructors can be exploited using a basic approach.

Naturally, destructors can be used in all sorts of clever ways in the context of a given PHP 5 application, mostly in those cases where it’s necessary to keep track of the status of certain objects prior to their being destroyed by the PHP interpreter. Nevertheless, this is undoubtedly a more complex topic that will be discussed in detail in upcoming articles of the series. So for the moment, I’m going to continue at my own pace, and consequently, in this second chapter you’ll learn how to work simultaneously with multiple classes that concretely implement their respective destructors.

The subject is indeed very interesting, so I think it’s time to move forward and keep learning more useful things concerning the usage of destructors with PHP 5. Let’s go!

{mospagebreak title=Handling user-related data with a simple PHP 5 class}

Before I teach you how to work with multiple classes that provide concrete implementation for each of their destructors, it’s convenient to refresh a few fundamental concepts concerning the use of them at a very basic level. To do so, I’m going to use the sample class that I constructed in the last tutorial. As you’ll recall, it came in handy for managing common user-related data, including first and last names and email addresses.

Essentially, the signature of this user handling class looked like this:

// 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>’;

}

}


Frankly speaking, I must say that the definition of the above “User” class is extremely easy to understand. So you shouldn’t have much of a problem grasping how it functions. However, I’d like you to pay close attention to the “__destruct()” method declared in the end. In this case, as with all of the magic methods provided by PHP 5, it’s preceded by two underscore (__) characters and indicates that the interpreter is going to execute it right before destroying an object created with this class.

This concept may sound rather confusing if it’s not accompanied by a practical example. Therefore, below I coded a simple script that spawns a new user object, displays its properties’ values on the browser, and then, as you’d expect, triggers the corresponding destructor prior to finishing its execution.

Having explained that, please take a look at 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();

 

/* 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

Destroying user now…

*/

}

catch(Exception $e){

echo $e->getMessage();

exit();

}


There you have it. Check the above example with your own testing web server and you’ll be amazed at how well it works! Perhaps it’s not going to change your life as a PHP programmer forever, but undoubtedly it’s going to show you how a destructor functions. In this case, the implementation of the destructor is rather primitive, yet this example should fire up your creativity so that you use your own class destructors in a more useful way.

Well, at this moment you’ve hopefully recalled the foundations of working with destructors in PHP 5. So assuming that this is true, the next thing that I’m going to teach you will be how to use multiple objects that concretely implement their respective destructors. In doing this, you’ll be able to see very clearly in what order these methods are called by the PHP interpreter right before the objects are destroyed.

To find out how this will be done, please visit the following section and keep reading.

{mospagebreak title=Working with multiple objects by redefining the destructor of the previous “User” class} 

Since my purpose here is to demonstrate how multiple destructors are called by the PHP parser, when working with several objects I’m going to modify the signature of the previous “User” class and more specifically, its destructor method.

Basically, the method in question will now be capable of indicating what object is being used before the PHP interpreter removes it from memory (destroyed, in crude terms). Now that you know the scenario, please take a look at the modified definition of the sample user class, which is as follows:

// define ‘User’ class (it provides a slightly more complete implementation of its destructor)

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>Warning! Destroying User: ‘.$this->firstName.’ ‘.$this->lastName.’<h2>’;

}

}


Now, the destructor method of the above “User” class has been provided with the capacity for displaying on the browser the first and last name properties of the object that is about to be destroyed. This is convenient for finding out the order in which destructors are called when using multiple objects.

At this stage, having improved the implementation of the destructor that belongs to the previous user class, it’s appropriate for you to read the next section of the article. In it you’ll learn how to keep track of the order used by the PHP parser to call several destructors when using different user objects.

This juicy topic will be discussed in detail in the next few lines, so go ahead and read them please.

{mospagebreak title=Finding out the order in which several destructors are called by the PHP interpreter}

In consonance with the concepts I deployed in the section you just read, I’m going to code a basic script that will create multiple instances of the “User” class that you saw previously. Then, it will echo on the browser the respective first and last names of these user objects just created. And finally, it will finish its normal execution.

However, since each of these objects implements a destructor, they will be called logically by the PHP parser, which will also help you know the order in which the respective destructors are invoked before the objects in question are destroyed. Sounds like a simple yet educational experiment, right?

Having said that, here’s the script that works with multiple destructors, so study its source code:

try{

// create first user

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

// display separately user data

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

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

echo ‘Email: ‘.$user1->getEmail().’<br />’;

// display all user information

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

 

// create second user

$user2=new User(‘Mary’,'Smith’,'mary@domain.com’);

// display separately user data

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

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

echo ‘Email: ‘.$user2->getEmail().’<br />’;

// display all user information

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

 

// create third user

$user3=new User(‘Susan’,'Norton’,'susan@domain.com’);

// display separately user data

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

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

echo ‘Email: ‘.$user3->getEmail().’<br />’;

// display all user information

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

 

 

}

catch(Exception $e){

echo $e->getMessage();

exit();

}

As you can see in the above example, three different objects are created using the corresponding “User” class, and then their properties are outputted to the browser. Finally, the program stops its execution. So far, nothing unexpected happens. But if you look into the output generated by the previous script, guess what? Yes, you’re correct! Their pertinent destructors are called up in the same order used to spawn the originating objects.

This process is clearly demonstrated by the following listing:

First Name: John

Last Name: Doe

Email: john@domain.com

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


First Name: Mary

Last Name: Smith

Email: mary@domain.com

Complete user information: First Name: Mary Last Name: Smith Email Address: mary@domain.com


First Name: Susan

Last Name: Norton

Email: susan@domain.com

Complete user information: First Name: Susan Last Name: Norton Email Address: susan@domain.com

 

Warning! Destroying User: John Doe

Warning! Destroying User: Mary Smith

Warning! Destroying User: Susan Norton


At this point, I’ve provided you with an instructive example on how to work with multiple objects that concretely implement their corresponding destructors, a process that came in handy for seeing the order in which they’re called by the PHP interpreter.

My final recommendation concerning the use of destructors is that you develop your own test examples based on the concepts that you learn in this article series. You’re going to have fun, trust me!

Final thoughts

In this second installment of the series, I went a bit deeper into the implementation of destructors with PHP 5 and showed you how to keep track of the order in which these class methods are invoked by the PHP engine when working with multiple objects.

In the upcoming article, I’m going to teach you how to define destructors in such a way that they can display useful information about a particular object prior to being destroyed by the PHP interpreter.

Want to learn how this will be done? Don’t miss the next part!

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