PHP
  Home arrow PHP arrow Page 5 - 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 a method call: triggering the “__call()” method
    ( Page 5 of 5 )

    The last practical example that I’ll show you with reference to overloading classes in PHP 5 is completely focused on calling the “__call()” method automatically, when a method call is correctly overloaded. Maybe this sounds confusing, so first I’ll redefine the prior “DataSaver” class to provide a concrete definition for the “__call()” method that I mentioned before. Here’s the source code for this class:

    class DataSaver{
        private $data=array('Element1'=>1,'Element2'=>2,'Element3'=>3);
        private $dataFile='default_data_file.txt';
        // define __call() method
        public function __call($method,$arguments){
            echo 'Method '.$method. ' has been called with the
    following arguments:<br />';
            foreach($arguments as $argument){
                echo $argument.'<br />';
            }
            return array_reverse($arguments);

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

    As shown above, the “DataSaver” class has an additional “__call()” method, which will be automatically triggered if a method call is overloaded deliberately. Given that, here is a simple script that shows how to overload a method call, which obviously fires up the method in question:

    // example of method overloading with __call() method
    try{
        // instantiate 'DataSaver' object
        $dataSaver=new DataSaver();
        // call inexistent 'myMethod()' method (invokes the __call()
    method)
        $revData=$dataSaver->myMethod('Element A','Element
    B','Element C');
        echo 'Reversed arguments are as follows:<br />';
        foreach($revData as $data){
            echo $data.'<br />';
        }
    }
    catch(Exception $e){
        echo $e->getMessage();
        exit();
    }

    If you examine the above example  in detail, the corresponding “__call()” method is triggered by the following line:

    $revData=$dataSaver->myMethod('Element A','Element B','Element
    C');

    As you can see, all that this line does is call the “myMethod()” method, in this way enforcing the triggering of “__call()”. Also, it should be noticed that the pertinent arguments passed when overloading a method call will be treated as an array, therefore the output produced by the previous script will be the following:

    Method myMethod has been called with the following arguments:
    Element A
    Element B
    Element C
    Reversed arguments are as follows:
    Element C
    Element B
    Element A

    The above listing clearly demonstrates that the  “__call()” method has been triggered after overloading a method call, since the array of incoming arguments is first echoed normally, then reversed and finally displayed again, in accordance with the logic implemented by this method.

    At this point, I provided you with different practical examples of how to overload members and methods in PHP 5, which can be pretty useful if you want to run custom code defined within  “__set()”, “__get()” and “__call()” methods. As I said before, certainly class overloading isn’t one of the strongest features of PHP, but with a little bit of willpower and the appropriate knowledge, you’ll get the most out of it.

    Wrapping up

    Over this three-part series, you hopefully learned the basics of class overloading in PHP 4/PHP 5. In all the cases I kept the code samples simple and readable, so you can understand more easily how they work. Although overloading objects in PHP seems to be a rather complex topic at first glance, this impression should disappear progressively, if you get more experience on the subject.

    As usual, see you in the next PHP tutorial!  



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

       

    PHP ARTICLES

    - 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
    - Method Chaining: Adding More Methods to the ...





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