HomePHP Using Abstract Classes to Build Polymorphs in PHP 5
Using Abstract Classes to Build Polymorphs in PHP 5
In this third part of a seven-part series, I demonstrate how to build polymorph objects using abstract classes in PHP 5. As you'll see, it's a pretty straightforward process that can be tackled with relative ease.
Learning how to build polymorph objects in PHP 5 is one of those topics that must be tackled sooner or later by those developers who want to expand their skills in using the object-oriented paradigm for creating web applications.
So, if you’re a PHP programmer looking for a friendly guide that shows you how to take advantage of the functionality provided by Polymorphism, then don’t hesitate anymore and start reading this series of articles right away!
In simple terms, there are two approaches that can be used for achieving Polymorphism in PHP 5, due to the weakly-typed nature of the language. The first one consists of defining one or many interfaces whose generic methods are inherited by the class or classes that implement those interfaces. This process is not surprisingly known as “Polymorphism via interfaces.”
The other methodology is certainly the most popular. It's based upon defining first a parent class, and then deriving as many subclasses as needed from it. These subclasses will reveal different behaviors, even if they implement the same method defined by the corresponding parent.
In the preceding tutorial of this series I demonstrated how to build polymorph objects by using a single interface. In that particular case, the interface declared four methods for outlining the structure of a generic HTML element object. With this interface settled on top of the hierarchy, it was really easy to create two classes that implemented its methods to construct HTML divs and paragraphs in a few steps.
However, as I said before, the most typical way to build polymorph objects in PHP is by way of one or more parent classes. You've probably done this hundreds of times before. Anyway, since this approach deserves a closer look, in the next few lines I’m going to show you how to render HTML divs on screen by using a simple abstract class.
Are you ready to learn more about how this will be accomplished? Then, go ahead and begin reading!