HomePHP Page 4 - Creating a Subclass for Building Polymorphs in PHP
The functionality of a polymorph object - PHP
Welcome to the fourth installment of an article series on building polymorphs in PHP. Made up of seven tutorials, this series attempts to teach you through numerous, comprehensive code samples how to create polymorph objects. You'll see how to do it using interfaces, then abstract classes, and finally a combination of both.
It’s quite possible that your concept on building polymorph objects via abstract classes is now spot on. However, for the sake of completeness, I'm going to develop a trivial script that demonstrates the actual functionality of the “Paragraph” subclass that you learned in the previous segment.
Having said that, here’s how this final script looks:
// create new instance of Paragraph class
$par = new Paragraph();
// assign attributes and content for paragraph element and display it on the browser
echo $par->setId('parid')->setClass('parclass')->setContent('This is the new content for the paragraph.')->render();
Simple to code but pretty illustrative, right? Definitely, there’s not much that can be said about the way that the “Paragraph” class works when using an instance of it, except for its behavior in response to a call to its “render()” method.
If you compare this basic example with the one that showed how to use the “Div” class, then you’ll realize why these two subclasses are considered polymorphs. Of course, it’s possible to create more subclasses that implement the “render()” method differently, but this will be left as homework for you, if you're feeling bored and look for something really fun.
That’s all for now. In this fourth chapter of the series, you learned how to take advantage of Polymorphism in PHP 5 by using a single abstract class and a couple of subclasses. As you saw for yourself, this process was indeed a no-brainer, so you shouldn’t have major problems understanding its driving logic.
Now, go back for a moment in time and recall the concepts deployed in the two first articles of the series. Remember that I discussed the construction of polymorph objects by using interfaces? That was a good experience, but in the real world, it is often necessary to build polymorph classes that inherit methods from both interfaces and parent classes simultaneously. This is a powerful approach.
Therefore, in the next article I’m going to show you how to apply this handy method with the pair of HTML element classes that you saw previously. Don’t miss the upcoming part!