HomePHP Page 4 - Rendering HTML Paragraphs with Polymorphs in PHP 5
A polymorph class in action - PHP
In this second article in a seven-part series on building polymorphs in PHP 5, I provide you with another example of how to do this by way of a simple interface. For this tutorial, I decided to work with objects that are responsible for rendering different HTML elements, such as div and paragraphs, but naturally itís possible to construct these types of object for different purposes as well.
If you're anything like me, then most likely you'll want to see how the "Paragraph" class defined in the previous segment can be put to work in a concrete context. With that idea in mind, below I coded a simple script that shows how to display a basic HTML paragraph on screen by using the chainable API of the aforementioned class.
Here's the script in question:
// create new instance of Paragraph class
$par = new Paragraph();
// assign attributes and content for paragraph element and display it on the browser
->setContent('This is the new content for the paragraph.')
The purpose in coding a script like this is not showing how to create basic paragraphs here and there; that would be pointless. Here, the relevant thing is the approach used for building polymorph objects, which involves a simple interface and a couple of implementer classes.
Of course, since in PHP 5 classes can implement multiple interfaces, it's possible to take advantages of Polymorphism by inheriting generic methods from several sources, even when these methods must be concretely implemented by the pertinent classes.
In this second episode of this series, I provided you with another concrete example that showed how to build polymorph objects in PHP 5 by way of a simple interface. For this tutorial, I decided to work with objects that are responsible for rendering different HTML elements, such as div and paragraphs, but naturally it's possible to construct this type of object for different purposes as well.
In the upcoming part, I'm going to explore another approach for achieving Polymorphism in PHP 5. You'll surely find it very familiar, since it will involve working with abstract classes.