PHP
  Home arrow PHP arrow Page 4 - Implementing Property Overloading in PHP 4
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? 
PHP

Implementing Property Overloading in PHP 4
By: Alejandro Gervasio
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: starstarstarstarstar / 6
    2006-07-11


    Table of Contents:
  • Implementing Property Overloading in PHP 4
  • Overloading a property access: using the “__set()” method
  • Overloading a PHP 4 class: using the native “overload()” function
  • Going deeper into property access overloading: using the “__get()” method

  • 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


    Implementing Property Overloading in PHP 4 - Going deeper into property access overloading: using the “__get()” method
    ( Page 4 of 4 )

    Remember that I said it was also possible to trigger a “__get()” method when a property access is overloaded? Fine, because that is what I’d like to show you in this section of the tutorial.

    In order to demonstrate how this process is performed, I’ll redefine the previous “CookieSaver” class, this time replacing its “__set()” method by a “__get()” method. This really sounds simple, so here’s the source code of the modified class:

    // define 'CookieSaver' class and implement __get() method
    class CookieSaver{
        var $cookieName;
        var $value;
        var $expTimes=array('exp1'=>900,'exp2'=>1800,'exp3'=>3600);
        function CookieSaver
    ($cookieName='defaultCookie',$value='defaultValue'){
            if(!is_string($cookieName)){
                trigger_error('Invalid cookie name',E_USER_ERROR);
            }
            $this->cookieName=$cookieName;
            $this->value=$value;
        }
        // set cookie
        function setCookie(){
            setcookie($this->cookieName,$this->value);
        }
        // get cookie
        function getCookie(){
            if(!$cookie=$_COOKIE[$this->cookieName]){
                trigger_error('Error retrieving
    cookie',E_USER_ERROR);
            }
            return $cookie;
        }
        // get value of property via __get() method
        function __get($property){
            $expTime=$this->expTimes[$property];
            setcookie('newCookie',urlencode('This cookie has been set
    via the __get() method'),time()+$expTime);
            echo 'Retrieving new cookie...with an expiration of
    '.$expTime.' seconds.';
            return;
        }
    }

    As I illustrated above, now the “CookieSaver” class specifically implements a “__get()” method, instead of exposing the previous “__set()” method that you learned before. Also, notice that the definitions of the remaining methods are the same, which means obviously that the class sets and retrieves a simple cookie via its “setCookie()” and “getCookie()” methods respectively.

    As you can see, now the “__get()” method has been defined in such a way that it retrieves a specific element of the $expTimes array and assigns this value to the expiry of the cookie in question. From this example, you’ll surely realize that the generic signature of a “__get()” method is the following:

    __get($property){
        // method definition goes here
    }

    By this point, after the prior __”get()” method has been explicitly implemented, it’s time to see how it can be triggered, overloading a specific property access. The code snippet below shows the process that calls the “__get()” method, when a property access is performed:

    // overload 'CookieSaver' class
    overload('CookieSaver');
    // instantiate 'CookieSaver' object
    $cookieSaver=&new CookieSaver();
    // set cookie
    $cookieSaver->setCookie();
    // call __get() method and retrieve $this->expTimes['exp1'] array element
    echo @$cookieSaver->exp1;

    In the above example, the “CookieSaver” class is first overloaded by using the “overload()” function, and then the “__get()” method is triggered by the property accessing line listed below:

    echo @$cookieSaver->exp1;

    This statement executes the code defined inside of the “__get()” method, which results in the following output:

    Retrieving new cookie...with an expiration of 900 seconds.

    In a similar way, it’s perfectly feasible to access the remaining elements of the $expTimes array, like this:

    // call __get() method and retrieve $this->expTimes['exp2'] array
    element
    echo @$cookieSaver->exp2;
    // call __get() method and retrieve $this->expTimes['exp3'] array
    element
    echo $cookieSaver->exp3;

    In both cases, the “__get()” method is automatically called and the output produced by the previous examples is the following:

    Retrieving new cookie...with an expiration of 1800 seconds.
    Retrieving new cookie...with an expiration of 3600 seconds.
     

    As you’ll realize, the PHP parser automatically triggers the execution of the “__get()” method, if there’s a line of code that overloads a property access, just like the examples shown a few lines above.

    At this stage, I hope that you already understand the logic that surrounds the overloading of classes in PHP 4. Even when the examples are just that, they show in a simple way how to execute custom code without having to explicitly call both “__set()” and “__get()” methods. Certainly, there’s plenty of room to experiment with this concept, and you’ll probably find more useful applications when overloading your PHP classes.

    To wrap up

    In this first part of the series, I explored the implementation of class overloading in PHP 4, specifically using the “overload()” function, which comes in handy for triggering “__set()” and  “__get()” methods, when a property access is overloaded.

    However, we’re just beginning the journey. Over the next tutorial, I’ll explain how to combine the two “__set()” and “__get()” methods inside the same class, as well as how to trigger the “__call()” function via method call overloading. You don’t have any excuses to miss it! 



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

       

    PHP ARTICLES

    - Using Directory Iterators to Build Loader Ap...
    - Using the spl_autoload() Functions to Build ...
    - Working Out of the Object Context to Build L...
    - Using the _autoload() Magic Function to Buil...
    - The Destruct Magic Function in PHP 5
    - The Autoload Magic Function in PHP 5
    - Developing a Recursive Loading Class for Loa...
    - The Sleep and Wakeup Magic Functions in PHP 5
    - Using the Clone Magic Function in PHP 5
    - Including Files Recursively with Loader Appl...
    - The Call Magic Function in PHP 5
    - Designing a Captcha System with PHP and MySQL
    - Using Static Methods to Build Loader Apps in...
    - The Isset and Unset Magic Functions in PHP 5
    - Advanced PHP Form Input Validation to Check ...





    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 6 hosted by Hostway
    Stay green...Green IT