HomePHP Page 4 - Building Dynamic Web Pages with Polymorphism in PHP 5
Seeing some polymorphic objects in action - PHP
If you’re starting to delve deeper into object-oriented programming with PHP, and also want to know how to include polymorphic objects into your own scripts, this might be the right opportunity to learn more about this interesting topic. Welcome to the second part of the series that began with “Using polymorphism with objects in PHP 5.” In three articles, this series provides you with a comprehensive guide on how to take advantage of polymorphism to build more efficient object-based PHP applications.
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!