PHP
  Home arrow PHP arrow Page 4 - Overloading Classes 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

Overloading Classes in PHP 5
By: Alejandro Gervasio
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: starstarstarstarstar / 7
    2006-07-25


    Table of Contents:
  • Overloading Classes in PHP 5
  • Overloading a property access in PHP 5: calling the “__set()” method
  • More about members overloading: triggering automatically the “__get()” method
  • Overloading multiple member accesses: combining the “__set()” and “__get()” method in the same class
  • Overloading a method call: triggering the “__call()” 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


    Overloading Classes in PHP 5 - Overloading multiple member accesses: combining the “__set()” and “__get()” method in the same class
    ( Page 4 of 5 )

    Assuming that you already understand the logic for triggering the “__set()” and “__get()” methods individually, combining them into the same class is just a matter of including the signature for each of them within the class you’re going to use. After adding these two methods, the definition of the “DataSaver” class looks like this:

    class DataSaver{
        private $data=array('Element1'=>1,'Element2'=>2,'Element3'=>3);
        private $dataFile='default_data_file.txt';
        // define __set() method
        public function __set($index,$value){
            echo 'Assigning value '.'''.$value.'''. ' to element
    with index='.$index.'<br />';
            if(!$this->data[$index]){
                throw new Exception('The referenced element is not
    valid');
            }
            $this->data[$index]=$value;
        }
        // define __get() method
        public function __get($index){
            echo 'Retrieving element of $data property with
    index='.$index.'<br />';
            if(!$this->data[$index]){
                throw new Exception('The referenced element is not
    valid');
            }
            return $this->data[$index];
        }
        // save data to file
        public function save(){
            if(!$fp=fopen($this->dataFile,'a+')){
                throw new Exception('Error opening data file');
            }
            fwrite($fp,serialize($this->data));
            fclose($fp);
        }
        // fetch data from file
        public function open(){
            if(!$contents=file_get_contents($this->dataFile)){
                throw new Exception('Error reading from data file');
            }
            return unserialize($contents);
        }
    }

    At this point, the above class exposes the “__set()” and “__get()” method conjunctly, which comes in very handy for being triggered when overloading two property accesses. This process is illustrated below:

    // example of __set() and __get() overloading
    try{
        // instantiate 'DataSaver' object
        $dataSaver=new DataSaver();
        // change one element of $data property (calls the __set()
    method)
        $dataSaver->Element2='This is element 2';
        // fetch element of $data property (calls the __get() method)
        echo 'The value of the following element property is
    '.$dataSaver->Element1;
    }
    catch(Exception $e){
        echo $e->getMessage();
        exit();
    }

    In this example, I overloaded two property accesses, in order to trigger in turn the “__set()” and “__get()” methods. I deliberately kept the code simple and readable, so you can see clearly how both methods are called in the script’s context, in addition to examining what type of output is generated by each of them.

    All right, after executing the previous code snippet, the following messages are displayed sequentially:

    Assigning value 'This is element 2' to element with
    index=Element2
    Retrieving element of $data property with index=Element1
    The value of the following property is 1

    Even when the example you saw before is rather trivial, it does demonstrate how two specific property accesses can be overloaded, resulting in the execution of the “__set()” and “__get()” methods respectively.

    Do you think we’re done now? Not yet. I want to conclude this article showing you a simple example of how to overload a method call in PHP 5, which can be useful for triggering custom code wrapped into a “__call()” method. Therefore, go ahead and read the next few lines to see how this will be achieved.



     
     
    >>> 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 4 Hosted by Hostway
    For more Enterprise Application Development news, visit eWeek