Home arrow PHP arrow Page 4 - Abstract Classes in PHP: Working with PHP 5

Using abstract classes in PHP 5: setting up an example - PHP

Here we are again. This is the tutorial you’ve been waiting for! Welcome to the last part of the series “Abstract classes in PHP.” If you’ve already read the previous articles, then you’ll know that this series introduces the basics of abstract classes in PHP 4/PHP 5, and illustrates their use and implementation in concrete situations.

TABLE OF CONTENTS:
  1. Abstract Classes in PHP: Working with PHP 5
  2. Working with a highly improved object model: defining abstract classes in PHP 5
  3. Calling class methods out of the object context: using the scope resolution operator
  4. Using abstract classes in PHP 5: setting up an example
By: Alejandro Gervasio
Rating: starstarstarstarstar / 50
February 08, 2006

print this article
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement

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
 

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort
   

PHP ARTICLES

- Hackers Compromise PHP Sites to Launch Attac...
- Red Hat, Zend Form OpenShift PaaS Alliance
- PHP IDE News
- BCD, Zend Extend PHP Partnership
- PHP FAQ Highlight
- PHP Creator Didn't Set Out to Create a Langu...
- PHP Trends Revealed in Zend Study
- PHP: Best Methods for Running Scheduled Jobs
- PHP Array Functions: array_change_key_case
- PHP array_combine Function
- PHP array_chunk Function
- PHP Closures as View Helpers: Lazy-Loading F...
- Using PHP Closures as View Helpers
- PHP File and Operating System Program Execut...
- PHP: Effects of Wrapping Code in Class Const...

Developer Shed Affiliates

 


Dev Shed Tutorial Topics: