PHP
  Home arrow PHP arrow Page 2 - Overloading Classes in PHP 5
Administration  
AJAX  
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 
Sun Developer Network 
E-Commerce Hosting 
Linux Web Hosting 
Managed Hosting 
Small Business Hosting 
Mobile Linux 
App Generation ROI 
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

Overloading Classes in PHP 5
By: Alejandro Gervasio
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 4 stars4 stars4 stars4 stars4 stars / 4
    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:
      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


    Overloading Classes in PHP 5 - Overloading a property access in PHP 5: calling the “__set()” method


    (Page 2 of 5 )

    Undoubtedly, the most significant difference between overloading classes in PHP 4 and PHP 5 rests on the native support offered by the last incarnation of PHP. True to form, PHP 5 will allow you overload your classes without having to use specifically the “overload()” function that was explained in previous articles.

    In order to demonstrate how a property access can be overloaded in PHP 5, first I need to have a sample class to work with, so I’ll define one. In this case, the “DataSaver” class that I’ll use on different examples 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;
            if(!$this->data[$index]){
                throw new Exception('The referenced element is not
    valid');
            }
            $this->data[$index]=$value;
        }
        // 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 you can see, the “DataSaver” class that I coded above looks really simple. What it does basically is save a serialized $data array to a text file and retrieve from it after reversing (unserializing) the process. However, aside from coding the corresponding “save()” and “open()” methods for performing these tasks, I provided a concrete implementation for a “__set()” method, which can be called automatically when a property access is overloaded. How is this done? Please take a look at the following example:

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

    In this case, the example shown above first instantiates a new “DataSaver” object and then triggers the respective “__set()” method, by overloading a property access through the following line:

    $dataSaver->Element1='This is element 1';

    As you probably realized, the above sample class was overloaded without the need to use the “overload()” function, since PHP 5 comes with native support for overloading “__set()”, “__get()” and “__call()” methods. Additionally, PHP 5.1.0 also supports transparent overloading of the “isset()” and “unset()” functions via the “__isset()” and “__unset()” methods respectively, but since they won’t be covered in this article for the moment, you can learn more about this by reading the PHP manual.

    With reference to the example shown before, after overloading a member access, the corresponding “__set()” method is called, resulting in the following output:

    Assigning value 'This is element 1' to element with
    index=Element1

    The message listed above shows how the “__set()” method is successfully triggered when a property access is appropriately overloaded.

    However, this tells only half of the story, since it’s also possible to call automatically a “__get()” method -- provided that it was previously defined within the corresponding class -- when a property access is overloaded. That’s precisely what I’ll teach you in the next section, therefore click on the link below and keep reading.

    More PHP Articles
    More By Alejandro Gervasio


       · Over this last part of the series, you'll learn how to overload classes in PHP 5....
     

       

    PHP ARTICLES

    - Working With Different Namespaces in PHP 5
    - User Management Explained: Overview
    - Using Namespaces in PHP 5
    - Database Security: Guarding Against SQL Inje...
    - Building a Modular Exception Class in PHP 5
    - Database and Password Security for Web Appli...
    - Handling MySQL Data Set Failures in PHP 5
    - Building Site Registration for Web Applicati...
    - Intercepting Customized Exceptions in PHP 5
    - Securing Your Web Application Against Attacks
    - Sub Classing Exceptions in PHP 5
    - Authentication for Web Application Security
    - Building a Content Management System with Co...
    - Filters and Login Systems for Web Applicatio...
    - Working with the Email Class in Code Igniter





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