Keeping Track of Objects when Using Destructors in PHP 5

Among the improvements that were introduced into the object model of PHP 5, class destructors are quite possibly, one of the easiest to learn and implement. As you may have heard, a destructor is a special kind of method that is called automatically by the PHP interpreter right before destroying a particular object. So if you’re interested in learning how to use them in your own PHP 5-driven applications, you should start reading this article series!

This is the third chapter of the series “Understanding destructors in PHP 5.” In the different tutorials that comprise the series, you’ll find the right pointers to start utilizing destructors within your PHP 5 classes. And in addition to learning the corresponding theory regarding these useful methods, you’ll be provided with copious hands-on examples aimed at demonstrating, in a practical way, how to get the most out of them.

Now that you’re well aware of the main subject of this series, I’m going to take a few minutes of your valuable time to rehash the topics that were discussed in the last article. As you’ll probably recall, during the course of that article, I went through the definition of a highly generic user handling class, which when implemented at a basic level, is a primitive destructor method.

The purpose was simply to demonstrate the order in which multiple destructors were called by the PHP interpreter, when using some of the user handling objects that I mentioned earlier. The final result of this testing process was pretty obvious: the PHP engine used the same order in which these objects were constructed, to destroy them; something that was clearly shown by the respective destructors.

Even though this particular example doesn’t have a direct application in real world conditions, it should help you understand the priority scale used by the PHP parser when it comes to calling multiple destructors during the execution of a given application.

So far, so good. Now that you hopefully remember all the details concerning the use of several destructors in PHP 5, it’s time to continue learning more about these helpful methods. Therefore, in this third part of the series, I’m going to show you how to retrieve some useful information about a specific object, including its properties and methods, prior to its being destroyed by the PHP parser via the implementation of a simple destructor.

Want to see how this will be achieved? Jump into the next few lines and begin reading now!

{mospagebreak title=When the order really matters: working with multiple destructors}

There’s the possibility that by the time you read the introduction of this article, using multiple destructors in the same PHP 5 application will be a well-known process for you, since this particular situation was analyzed in detail in the previous article of the series.

However, if you didn’t have the chance to go through that specific tutorial, you might want to take a close look at the following PHP 5 script, which precisely recreates a hypothetical scenario in which several user handling objects are first spawned from a sample “User” class, and then destroyed when the script in question finishes its execution.

Although it’s obvious, the most relevant thing to highlight here is that all these objects implement a destructor concretely, which is then called in the proper sequence by the PHP 5 interpreter prior to being removed from the web server’s memory.

That being said, here’s the signature of the aforementioned “User” class, so examine it closely:


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

}

}


Undeniably, the definition of the prior “User” class is very straightforward, so I assume that you shouldn’t have much trouble understanding how it works. You should pay special attention, though, to the implementation of its destructor method, which as you can see, is capable of outputting the values of some class properties, such as the ones named ($firstName and $lastName), when automatically called by the PHP parser.

With such a useful destructor method at your disposal, it’s perfectly possible to build a sample script that first creates different user-related objects, and then displays the data of the current object being destroyed. In this way it constructs an effective mechanism that demonstrates the order followed by the PHP engine to call up the respective destructors.

With this idea in mind, below I coded this simple example, which works with multiple objects and destructors. Here it is:


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();

}


// output generated by the previous script


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


That was pretty easy to grasp! In this case, all the destructors corresponding to the previous user handling objects will be invoked in the same order utilized for creating them. Certainly this is a procedure demonstrated by the above script’s output.

So far, everything seems to be fine, because you’ve hopefully learned how to work with several objects that concretely implement their respective destructors. However, now that you’ve digested all this useful material, it’s more than probable that you might have asked yourself the following question: is it possible to implement a destructor that can keep track of the properties and methods of a determined object prior to its merciless destruction? (That was pretty dramatic…) Well, the answer is an emphatic yes! And bearing this in mind, in the next section I’m going to show you how to modify the destructor of the same “User” class defined previously so it can provide detailed information about a particular object right before that object is destroyed by the PHP engine.

To see how this will be done, please click on the link below and keep reading.

{mospagebreak title=Retrieving useful information about a particular object before it’s removed}

In accordance with the concepts that I deployed in the section you just read, I’m going to modify the destructor of the sample “User” class that you learned previously so that it can display some useful information, such as methods and properties, about an object that is about to be destroyed.

To achieve this process as painlessly as possible, below I included the improved definition of the “User” class, which this time implements its destructor in a more useful way. Have a close look at its definition, please:


// 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(){

// display object properties

echo ‘<h2>Properties of object being destroyed</h2>';

foreach(get_object_vars($this) as $prop=>$val) {

 echo ‘<p>’.$prop.’=’.$val.'</p>';

 }

// display object methods

echo ‘<h2>Methods of object being destroyed</h2>';

$methods=get_class_methods(get_class($this));

foreach($methods as $method) {

echo ‘<p> Method Name: ‘.$method.'()</p>';

}

}

}


As you can see, things are getting really exciting now, since the above user handling class offers a more insightful implementation for its destructor. In this specific case, the destructor in question uses some well-known PHP native functions, like “get_object_vars()” and “get_class_methods(),” in order to display some useful information about a particular object prior to its deletion.

Of course, there is plenty of room to experiment and have fun here by implementing the destructor in different ways, according to your specific needs. But this hands-on example should give you an approximate idea of how to define a destructor that eventually provides relevant data on a specific object.

So far, so good. At this point I’ve already taught you how to implement a destructor and provide it with the ability to display the values of the methods and properties assigned to a specific object, right before its destruction.

However, if you’re as curious as me, then surely you’ll want to see how this method works in the context of a practical example. Therefore, in order to learn how this example will be constructed, please visit the following section. It’s only one click away.

{mospagebreak title=Seeing the improved User class in action}

In the course of the previous section, I showed you how take advantage of the destructor that corresponds to the sample “User” class in order to display a few relevant values of a particular object, prior to its being removed from the web server’s memory.

Based upon the improved implementation of this method, in the next few lines I coded an illustrative example, which, as you’d expect, first spawns a new user handling object from the previous “User” class, and then outputs to the browser the names of the methods and properties assigned to it, right before being deleted by the PHP interpreter. In this way it constructs a primitive, yet effective, mechanism that comes in handy for tracking objects that are just about to be destroyed.

Now study the following example, which looks like this:


try{

// create user object

$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

 

Properties of object being destroyed

firstName=John

lastName=Doe

email=john@domain.com

 

Methods of object being destroyed

Method Name: __construct()

Method Name: getFirstName()

Method Name: getLastName()

Method Name: getEmail()

Method Name: getAll()

Method Name: __destruct()

 

*/

}

catch(Exception $e){

echo $e->getMessage();

exit();

}


See how simple it is to track objects with a simple destructor before they are deleted? I bet you do! In this specific case, this destructor is especially useful, because of its capacity to display on the browser the methods and properties of the object that will be removed.

However, as you’ll realize, the implementation of this method can be improved based on the example that you learned earlier. The same approach that I used here can be extended, for instance, to save the status of the object to a text file or a database table. The possibilities are really numerous. So what are you waiting for? Fire up your creativity and start taking advantage of destructors now!

Final thoughts

In this third installment of the series I went a bit deeper into the implementation of destructors with PHP 5 and showed you how to use this magic method to build a simple application that displays the properties and methods of a particular object prior to its corresponding deletion by the PHP interpreter.

In the next article of the series, I’ll teach you how to use the same approach shown in this article, but this time to keep track of multiple objects before being destroyed.

Curious about how this will be done? Don’t miss the next part!

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

antalya escort bayan antalya escort bayan Antalya escort diyarbakir escort