PHP
  Home arrow PHP arrow Page 4 - Executing Destructors Manually in PHP ...
Dev Shed Forums 
Administration  
Apache  
BrainDump  
DHTML  
Flash  
Java  
JavaScript  
Multimedia  
MySQL  
Oracle  
Perl  
PHP  
Practices  
Python  
Reviews  
Security  
Style-Sheets  
Web Services  
XML  
Zend  
Zope  
Forums Sitemap 
IBM® developerWorks 
Dedicated Servers 
E-Commerce Hosting 
Linux Web Hosting 
Managed Hosting 
Small Business Hosting 
Download TestComplete 
VPS Hosting 
Weekly Newsletter

 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
PHP

Executing Destructors Manually in PHP 5
By: Alejandro Gervasio
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 4 stars4 stars4 stars4 stars4 stars / 3
    2008-02-13

    Table of Contents:
  • Executing Destructors Manually in PHP 5
  • Triggering a destructor manually
  • Calling multiple destructors manually
  • Emulating destructors in PHP 4

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
     
    ADVERTISEMENT

    TestComplete™ automates software testing for a fraction of what the big guys charge. Easy functional and load testing for all Windows, .NET, Java and Web apps. Download a free trial now.

    Executing Destructors Manually in PHP 5 - Emulating destructors in PHP 4
    (Page 4 of 4 )

    While PHP 4 indeed doesn’t directly support the implementation of destructors, as does PHP 5, the behavior of these methods can be emulated by using the PHP “register_shutdown_function()” function, which, as its name suggests, permits it to specify what user-defined function will be called when a script terminates its execution.

    Of course, this function can be used with both procedural and object-oriented approaches. In this case I’m going to teach you how to use it within the same “User” class that you saw in previous sections, allowing the definition of a concrete method that will be invoked when a particular user handling object is destroyed by the PHP interpreter.

    Naturally, this behavior closely resembles the one exposed by a destructor in PHP 5. So in taking advantage of this, below I listed the signature of the prior “User” class in order to function with PHP 4. Here’s how the pertinent class now looks:


    // define 'User' class

    class User{

    var $firstName;

    var $lastName;

    var $email;

    function User($firstName,$lastName,$email){

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

    trigger_error('Invalid First Name parameter!',E_USER_ERROR);

    }

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

    trigger_error('Invalid Last Name parameter!',E_USER_ERROR);

    }

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

     trigger_error('Invalid Email parameter!',E_USER_ERROR);

    }

    $this->firstName=$firstName;

    $this->lastName=$lastName;

    $this->email=$email;

    register_shutdown_function(array($this,'customShutdown'));

    }

    // get user's first name

    function getFirstName(){

    return $this->firstName;

    }

    // get user's last name

    function getLastName(){

    return $this->lastName;

    }

    // get user's email

    function getEmail(){

    return $this->email;

    }

    // get all user data

    function getAll(){

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

    }

    // define class method for being called when the script finishes its execution

    function customShutdown(){

    // display object properties

    echo '<h2>Properties of current object</h2>';

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

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

    }

    // display object methods

    echo '<h2>Methods of current object</h2>';

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

    foreach($methods as $method) {

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

    }

    }

    }


    As you can see, at first sight the above user handling class looks very similar to its PHP 5 incarnation; however, you should pay attention to the definition of its constructor, since here is where all the action takes place. The following line within this class method:


    register_shutdown_function(array($this,'customShutdown'));


    indicates that a “customShutdown()” method will be called when an object of the “User” class is deleted, in this manner emulating the behavior of a real destructor. Quite simple, right?

    Assuming that you already grasped how to implement the PHP “register_shutdown_function()” as part of a class API, please study the following example, which demonstrates how the “customShutdown()” method is neatly called when a sample user object is destroyed by the PHP engine. Here it is:


    // create user object

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


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

    firstName=John

    lastName=Doe

    email=john@domain.com


    Methods of current object

    Method Name: User()

    Method Name: getFirstName()

    Method Name: getLastName()

    Method Name: getEmail()

    Method Name: getAll()

    Method Name: customShutdown()


    */


    In this case, you can see that the previous “User” class now has a method that closely resembles the behavior of the native destructor in PHP 5, since when the above script finishes running (and the pertinent user object is consequently deleted), the “customShutdown()” method is properly invoked.

    Here you have it. From this point onward, you may want try defining some classes with PHP 4 and implementing a few pseudo destructor methods within them. It’s going to be an instructive experience, believe me!

    Final thoughts

    It’s hard to believe, but we’ve come to the end of this series. Overall, the experience has been instructive and also fun. As you saw in the different tutorials, destructors aren’t going to change your life as a PHP developer forever, but they can be potentially useful in certain cases.

    Tracking the status of a bunch of objects is probably one of its most popular uses, but this doesn’t necessarily mean that they can only be applied to perform this task. So fire up your inspiration and start using destructors in a creative way!

    See you in the next PHP development tutorial!


    DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.

       · Over the course of this final episode of the series, you’ll learn you how to trigger...
     

       

    PHP ARTICLES

    - Comparing Files and Databases with PHP Bench...
    - Setting Up a Web-Based Image Gallery
    - Using Timers to Benchmark PHP Applications
    - Benchmarking Applications with PHP
    - Setting Up a Web-Based File Manager: PHPfile...
    - Developing a Modular Class For a PHP File Up...
    - Setting Up a Web-Based File Manager: bfExplo...
    - Defining a Custom Function for File Uploader...
    - Parsing Child Nodes with the DOM XML extensi...
    - Creating an Error Handling Module for a PHP ...
    - Accessing Attributes and Cloning Nodes with ...
    - Retrieving Information on Selected Files wit...
    - Handling HTML Strings and Files with the DOM...
    - Building File Uploaders with PHP 5
    - Working with Multiple Document Nodes with th...




    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 2 hosted by Hostway