I’d like to finish this last part of the series by coding another simple example that shows how the “render()” and “parseContent()” methods that belong to the previous “Div” and “Paragraph” classes can behave radically differently, even when called in the context of the same script. This particular hands-on example looks like this: // create new instance of Div class $div = new Div(); // assign attributes and content to div element and display it on the browser echo $div->setId('divid') ->setClass('divclass') ->setContent('<body>This is the new content for the div.</body>') ->parseContent() ->render();
// 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(); Hopefully with this final example, you’ll see for yourself that the “Div” and “Paragraph” classes shown previously are true polymorph structures. To demonstrate this concept more clearly, I modified the contents that are inputted into the “parseContent()” method of the classes, which will produce completely different results. Feel free to edit all of the code samples included in this tutorial. Doing so will help give you a better grounding in building polymorph objects in PHP 5. Final thoughts It’s hard to believe, but we’ve come to the end of this series. Hopefully this group of tutorials has been insightful for you. You learned how to achieve Polymorphism in PHP 5, first by using interfaces, then via abstract classes, and finally by combining these two structures simultaneously. At first glance, and particularly for developers taking their first steps in PHP-based web development, it seems that building polymorph objects is rather a pointless task. However, Polymorphism is indeed a powerful paradigm that will help you build solid, well-structured object-oriented applications. See you in the next PHP development tutorial!
blog comments powered by Disqus |
|
|
|
|
|
|
|