Understanding Destructors in PHP 5 - Testing the Previous User (
Page 4 of 4 )
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!