Building Dynamic Web Pages with Polymorphism in PHP 5 - Seeing some polymorphic objects in action
(Page 4 of 4 )
As I stated in the section that you just read, at this moment I'd like to create an educational example where all the classes that were defined previously are put to work in conjunction. As you'll see in the next few lines, the purpose of developing this example is to demonstrate how a small set of polymorphic objects can be used to create a complete web document.
But, I don't want to bore you with irrelevant details any longer, therefore pay attention to the following code sample, please:
try{
// build array of web page objects
$elements=array(new H1('This is an H1 header','',''),new H2
('This is an H2 header','',''),new H3('This is an H3
header','',''),new Paragraph('This is a
paragraph','parid','parclass'),new Div('This is a
DIV','divid','divclass'),new Link('This is a
link','linkid','linkclass','default,htm'));
// display web page elements using polymorphism
foreach($elements as $element){
echo $element->display();
}
}
catch(Exception $e){
echo $e->getMessage();
exit();
}
Even when the signature of the above script is short, it demonstrates in a nutshell how polymorphism can be used to generate a simple web page. Our page includes three headers and one paragraph, one containing DIV and finally a regular link.
Nonetheless, the most interesting detail to notice here is how the same "display()" method is called by the different web page objects within a "foreach" construct to build the web document in question. Precisely, this condition is demonstrated by the following code block:
foreach($elements as $element){
echo $element->display();
}
All right, now that you have learned how to take advantage of polymorphism, I suggest you start using this fundamental pillar of object-oriented programming when you build your own PHP applications.
Final thoughts
Sad but true, we've come to the end of this tutorial. In this second installment of the series, I provided you with a clear example of how to use polymorphic objects to build dynamic web documents.
However, if you think this educational journey has finished, I'm afraid you're wrong. There's still one last article to read, where I'll explain how to utilize the benefits of polymorphism to validate user-supplied data. You've been warned, so don't miss it!
| DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware. |