PHP
  Home arrow PHP arrow Page 4 - Abstract Classes in PHP: Working with 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? 
PHP

Abstract Classes in PHP: Working with PHP 5
By: Alejandro Gervasio
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: starstarstarstarstar / 27
    2006-02-08


    Table of Contents:
  • Abstract Classes in PHP: Working with PHP 5
  • Working with a highly improved object model: defining abstract classes in PHP 5
  • Calling class methods out of the object context: using the scope resolution operator
  • Using abstract classes in PHP 5: setting up an example

  • 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


    Abstract Classes in PHP: Working with PHP 5 - Using abstract classes in PHP 5: setting up an example
    ( Page 4 of 4 )

    The thing about abstract classes, though, is that all their related concepts are grasped better by studying some sample code. If you’re anything like me, you may want to see how an abstract class can be used in a more useful situation. Right, I’ll start developing an example, by defining a base abstract class named “dataSaver” (yeah, sometimes my creativity blows me away), which will reside on top of the hierarchy of classes, and expose an abstract “save()” method, useful for modeling generic behaviors for all “dataSaver” objects. Please, have a look at the signature of this class:

    abstract class dataSaver{
        protected $data;
        protected function setData($data){
            $this->data=$data;
        }
        // abstract 'save()' method
        abstract protected function save();
    }

    While the definition for the above class looks very straightforward, there are certain things worth highlighting. Aside from declaring this class abstract, notice the “protected” visibility assigned to class methods, as well as to the $data property. This means that class members can only be accessed from the originating class or from further child classes. See how I’m restricting the implementation of abstract methods only to the subclasses? I hope you do.

    Now the rule mentioned before should be clear: since the base abstract “dataSaver” class defines also an abstract method, not only must all its subclasses provide implementation for it, but its visibility must also be the same or weaker, which implies having to declare this method at least protected or public.

    Having defined the base “dataSaver” class, let’s leap forward and define a couple of subclasses, which will explicitly implement the abstract “save()” method. Here’s the definition for the first child class:

    class fileDataSaver extends dataSaver{
        private $file;
        public function __construct($data,$file){
            // call parent method 'setData()'
            parent::setData($data);
            $this->file=$file;
        }
        // save data to file
        public function save(){
            if(!$fp=fopen($this->file.'.txt','a')){
                throw new Exception('Error opening target file');
            }
            fwrite($fp,$this->data);
            fclose($fp);
        }
    }

    In this case, the “fileDataSaver” subclass provides implementation for the abstract “save()” method, and uses it for saving the data passed on to the constructor to a specified target file. Notice how this method has a weaker visibility (declared public) than the one assigned in the parent class.

    Now, let’s extend the current example and derive another subclass from “dataSaver.” This comes in quite useful for seeing a different implementation for the abstract “save()” method. This brand new child class is defined as follows:

    class cookieDataSaver extends dataSaver{
        private $cookie;
        public function __construct($data,$cookie){
            // call parent method 'setData()'
            parent::setData($data);
            $this->cookie=$cookie;
        }
        // save data to cookie
        public function save(){
            setcookie($this->cookie,$this->data);
        }
    }

     

    This class is fairly simple, but worth examining in detail, since it defines a new implementation for the “save()” method. In this case, the above class stores the content of the incoming $data parameter in a simple cookie, and additionally illustrates how to assign the correct visibility for the method in question.

    Finally, in case you’re wondering, here is the complete list of defined classes, conjunctly with the instantiation of both “fileDataSaver” and “cookieDataSaver” objects:

    // define abstract base class 'dataSaver'
    abstract class dataSaver{
        protected $data;
        protected function setData($data){
            $this->data=$data;
        }
        // abstract 'save()' method
        abstract protected function save();
    }
    // define concrete class 'fileDataSaver'
    class fileDataSaver extends dataSaver{
        private $file;
        public function __construct($data,$file){
            // call parent method 'setData()'
            parent::setData($data);
            $this->file=$file;
        }
        // save data to file
        public function save(){
            if(!$fp=fopen($this->file.'.txt','a')){
                throw new Exception('Error opening target file');
            }
            fwrite($fp,$this->data);
            fclose($fp);
        }
    }
    // define concrete class 'cookieDataSaver'
    class cookieDataSaver extends dataSaver{
        private $cookie;
        public function __construct($data,$cookie){
            // call parent method 'setData()'
            parent::setData($data);
            $this->cookie=$cookie;
        }
        // save data to cookie
        public function save(){
            setcookie($this->cookie,$this->data);
        }
    }
    try{
        // instantiate 'fileDataSaver' object
        $fileSaver=new fileDataSaver('This is file data'."\n",'datafile');
        // save data to file
        $fileSaver->save();
        // instantiate 'cookieDataSaver' object
        $cookieSaver=new cookieDataSaver('This is cookie
    data','testcookie');
        // save data to cookie
        $cookieSaver->save();
    }
    catch(Exception $e){
        echo $e->getMessage();
        exit();
    }

    At this point, I’ve shown you a concrete example of how to create and use an abstract class in PHP 5, by building a hierarchy of classes, where the base class defines generic object methods, and the respective subclasses provide a specific implementation for each of them. Even when the sample codes that I wrote here are pretty rudimentary, they can be used as the foundation for writing more complex applications. As you know, after digesting the appropriate theory, practice is what you’ll need most in these cases.

    Bottom line

    In this series, I hope you’ve expanded your grounding in object-oriented PHP, by understanding the creation and application of abstract classes. If you’re an experienced Web developer working on a website or application, you might find these articles quite useful in your next development effort. Otherwise, if you’re a beginning programmer, wanting to know how abstract classes fit into the OOP schema, I provided you with some handy illustrations for starting quickly on the subject. See you in the next tutorial!



     
     
    >>> 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 4 hosted by Hostway
    Stay green...Green IT