HomePHP Page 4 - Abstract Classes in PHP: Setting Up a Concrete Example
More subclasses ahead: defining the “fileProcessor” class - 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.
In order to keep the hierarchy of sample classes pretty balanced, I’m going to derive another child class from the parent “dataProcessor” class, so you can understand how the same generic methods can be implemented differently by this subclass. For this reason, I’ll define the “fileProcessor” class, whose signature is listed below:
class fileProcessor extends dataProcessor{ var $file; function fileProcessor($file){ if(!file_exists($file)){ trigger_error('Invalid file!',E_USER_ERROR); exit(); } $this->file=$file; } // returns filedata as string with <br /> tags function toString(){ return nl2br(file_get_contents($this->file)); } // returns file data as array function toArray(){ return file($this->file); } // returns file data as XML function toXML(){ $xml='<?xml version="1.0" encoding="iso-8859-1"?>'."\n"; $xml.='<filedata>'."\n"; $filedata=$this->toArray(); foreach($filedata as $row){ $xml.='<filenode>'.trim($row).'</filenode>'."\n"; } $xml.='</filedata>'; return $xml; } }
As you can see, here the above child class provides specific implementations for all the generic methods originally defined within the abstract class, which I find very useful for creating a simple file processor. Stripped down to its bare bones, this class accepts the name of the file for processing and uses each one of its respective methods for returning file data in different formats.
Even when all class methods are very simple and understandable, it’s worth noting how they perform different tasks, according to the specific implementation within the two subclasses that I just created.
Additionally, if you’re pretty familiar with the major pillars of object-oriented programming, then you’ll realize that both “resultProcessor” and “fileProcessor” classes will spawn polymorphic objects, since they use the same set of methods, but actually perform different operations. I'm sure you’ll agree with me that this is a very cool and powerful concept.
So far, I’ve derived two subclasses from one base abstract class, something that hopefully has contributed to expanding your knowledge of using abstract classes in PHP 4. However, wouldn’t it be a nice corollary for this article to include all the sample classes in one script and spawn some objects? Right, let’s jump into the next section and see how these classes work together.