HomePHP Page 2 - Abstract Classes in PHP: Setting Up a Concrete Example
Setting up a concrete example: Defining the hierarchy of classes - PHP
Welcome to part two of the series “Abstract classes in PHP.” In three tutorials, this series introduces the key concepts of abstract classes in PHP 4-PHP 5, and explores their application and use in different object-oriented development environments. Whether you’re an experienced PHP developer wanting to fill in some gaps related to abstract classes, or only a beginner starting to taste the power of object-based programming in PHP, hopefully you’ll find this series enjoyable and instructive.
To illustrate how you can implement abstract classes in a concrete situation, what I’ll do next is set up an example, which will create a well-structured hierarchy of classes aimed at processing data coming from distinct sources. On top of this hierarchy, I’ll define an abstract, highly generic data processing class, which for obvious reasons won’t be able to be instantiated. Additionally, this class will expose three generic methods for converting data to different formats, but won’t provide explicit definitions for each of them (known as abstract methods).
In accordance with the concepts deployed in the first tutorial of this series, I’ll derive two subclasses from the base abstract class, by providing a concrete definition for all the generic methods inherited from the corresponding parent class. Sounds confusing? It’s not at all. Trust me. I’ll begin by defining the base abstract class “dataProcessor()”, which looks like this:
// define abstract class ‘dataProcessor’ class dataProcessor{ function dataProcessor(){ if(get_class($this)=='dataProcessor'||! is_subclass_of($this)){ trigger_error('This class is abstract.It cannot be instantiated!',E_USER_ERROR); } } // define generic methods function toString(){} function toArray(){} function toXML(){} }
As the above example shows, the abstract “dataProcessor” class has three empty methods, “toString()”, “toArray()” and “toXML()” respectively, aside from the corresponding constructor. Meeting the requirements of abstract classes, these methods don’t expose a specific definition themselves, because the base class only outlines the properties and methods of generic “dataProcessor” objects. Any further definition of these methods will be specifically provided within the pertinent child classes, which will implement a determined behavior in accordance with the functionality expected of each derived subclass.
Once the abstract “dataProcessor” class has been defined, it’s easy to see that each subclass will expose a concrete definition for the “toString()”, “toArray()” and “toXML()” methods. Since this process will be understood best by example, let’s move on together and derive the first child class, which I’ve called “resultProcessor”, responsible for processing MySQL result sets.