PHP
  Home arrow PHP arrow Page 2 - Understanding Destructors in PHP 5
Dev Shed Forums  
Administration  
AJAX  
Apache  
BrainDump  
DHTML  
Flash  
Java  
JavaScript  
Multimedia  
MySQL  
Oracle  
Perl  
PHP  
Practices  
Python  
Reviews  
Security  
Smartphone Development  
Style-Sheets  
Web Services  
XML  
Zend  
Zope  
Mobile Linux  
App Generation ROI  
IBM® developerWorks  
Forums Sitemap  
E-Commerce Hosting  
Linux Web Hosting  
Managed Hosting  
Small Business Hosting  
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? 
Google.com  
PHP

Understanding Destructors in PHP 5
By: Alejandro Gervasio
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: starstarstarstarstar / 8
    2008-01-16


    Table of Contents:
  • Understanding Destructors in PHP 5
  • Building a Sample
  • Introducing Class Destructors
  • Testing the Previous User

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      error-file:tidyout.log Del.ici.ous error-file:tidyout.log Digg
      error-file:tidyout.log Blink error-file:tidyout.log Simpy
      error-file:tidyout.log Google error-file:tidyout.log Spurl
      error-file:tidyout.log Y! MyWeb error-file:tidyout.log 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


    Understanding Destructors in PHP 5 - Building a Sample
    ( Page 2 of 4 )


    Building a sample PHP 5 class that doesn’t use a destructor

    An adequate point to start demonstrating how to declare and use class destructors is to step on the opposite side of the river (yes, my metaphoric skills really amaze me all the time). By this I mean building a sample class that lacks a destructor method, as you’ve done probably hundreds of times when using classes in PHP 4.

    Having said that, suppose that a specific PHP application requires working with objects that represent a determined range of users. Based upon this fictional scenario, I’m going to define a generic class, called “User,” which is convenient for storing some common properties of these hypothetical users, such as their first and last names, and their email addresses as well.

    Basically, this class has the following signature:


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

    }

    }

    As shown above, the “User” class that I just defined exposes some basic properties, along with a group of accessing methods tasked with returning the values assigned to the properties to client code. So far, understanding how this class works isn’t going to make you lose your hair, right?

    After defining that simple “User” class, it’s time to see how it works in a concrete case, so let me show you a basic script that first creates a new user object, then assigns some trivial values to the pertinent properties, and finally outputs these values to the browser.

    The signature of the script looks like this:

    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

     

    */

     

    }

    catch(Exception $e){

    echo $e->getMessage();

    exit();

    }


    Until now, the class performs fairly well. As you can see in the previous example, a user object is created and its properties are accessed via the corresponding methods. What else could you ask for? Well, not so fast. Suppose for an instant that you need to serialize the entire object for debugging purposes, right before the script finishes its execution.

    This could be quickly done by defining an additional class method that performs this serialization process. However, in doing so, the method should be called explicitly, right? Here’s where class destructors come in, since in PHP 5 it’s possible to implement concretely a “__destruct()” method, which will be automatically called by the interpreter (not direct invocation is needed) before an object is destroyed.

    In this particular case, the above user object could simply use a destructor to serialize itself, prior to being removed from the web server’s memory. Sounds quite useful, doesn't it? All right, now that you've seen how to work with a generic user class that doesn’t declare a “__destruct()” method as part of its API, it’s time to learn how to implement a basic destructor within the aforementioned class.

    As you might have guessed, I’ll be analyzing destructors in the upcoming section, so go ahead and read it. It’s only one click away.



     
     
    >>> More PHP Articles          >>> More By Alejandro Gervasio
     

       

    PHP ARTICLES

    - Implementing Factory Methods in PHP 5
    - Merging a File Split for FTP Upload using PHP
    - Getting Data from Yahoo Site Explorer Inboun...
    - Method Chaining: Adding More Selecting Metho...
    - How to Split a File During an FTP Upload Usi...
    - Expanding a Custom CodeIgniter Library with ...
    - Using the Yahoo Site Explorer Inbound Links ...
    - Building a CodeIgniter Custom Library with M...
    - Building an E-mini Trading System Using PHP ...
    - Completing the MySQL Class with Method Chain...
    - Building Dynamic Queries with Chainable Meth...
    - PHP Encryption and Decryption Methods
    - Building a MySQL Abstraction Class with Meth...
    - Completing a Sample String Processor with Me...
    - Mastering WHILE Loops for PHP and MySQL





    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 1 Hosted by Hostway
    For more Enterprise Application Development news, visit eWeek