HomePHP Page 4 - Polymorphs in PHP: Using Interfaces and Abstract Classes to Construct HTML Paragraphs
The polymorph class in action - PHP
In this penultimate part of a seven-part series on building polymorphs in PHP 5, I demonstrate how easy it is to build polymorph objects that merge the functionality of abstract classes and the structure of interfaces. The entire creation process is simple enough that you shouldn’t have major problems grasping its underlying logic.
Undeniably, the best way to understand how the “Paragraph” polymorph class developed in the previous segment can be utilized in a useful fashion is by means of a concrete example. Thus, in the following lines I coded a script that creates an instance of this class for constructing a trivial HTML paragraph:
// create new instance of Paragraph class
$par = new Paragraph();
// assign attributes and content to paragraph element and display it on the browser
echo $par->setId('parid')
->setClass('parclass')
->setContent('<p>This is the new content for the paragraph.</p>')
->parseContent()
->render();
Due to the simplicity of the above code sample, I’m not going to waste your time (and mine) with boring explanations regarding its functioning. It’s valid to note here, though, that I deliberately passed a paragraph to the “setContent()” method, which is automatically stripped off, in response to the call to “parseContent().”
And with this example, I’m wrapping up this penultimate episode of the series. As always, you’re free to tweak the source code of the classes shown here, so you can improve your skills in building polymorph objects with PHP 5.
Final thoughts
In this penultimate part of the series, I demonstrated how easy it is to build in PHP polymorph objects that merge the functionality of abstract classes and the structure of interfaces. As you saw for yourself, the whole creation process was very simple, so in theory you shouldn’t have major problems grasping its underlying logic.
In the final chapter of this series, I’m going to show you how to put the previous “Div” and “Paragraph” polymorph classes to work side by side, so you can clearly see how they behave differently when used within the same script.