PHP
  Home arrow PHP arrow Page 4 - Abstract Classes in PHP: Working with ...
Dev Shed Forums 
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

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


    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!


    DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.

       · If you've been reading the previous articles of this series, probably you'll find...
     

       

    PHP ARTICLES

    - Authentication Scripts for a User Management...
    - Utilizing the Use Keyword for Namespaces in ...
    - Building a User Management Application
    - 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





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