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!
blog comments powered by Disqus |
|
|
|
|
|
|
|