As I promised in the previous segment, below I wrote a script that shows how to use the polymorph "Div" class to display a containing div on screen. Here's the corresponding code fragment: // create new instance of Div class $div = new Div(); // assign attributes and content for div element and display it on the browser $div->setId('myid'); $div->setClass('myclass'); $div->setContent('This is the new content for the div.'); echo $div->render();
That was easy to code, wasn't it? Due to the intuitive API of the "Div" class, it's really simple to create first an instance of it, then assign some trivial values to its properties via the pertinent setter methods, and finally render the div element on screen. In addition, since most of the methods of this class are chainable, it's feasible to rewrite the previous script a little bit more tightly, like this: // create new instance of Div class $div = new Div(); // assign attributes and content for div element and display it on the browser echo $div->setId('myid') ->setClass('myclass') ->setContent('This is the new content for the div.') ->render(); There you have it. Thanks to the neat support offered by PHP 5 for working with interfaces, building polymorph classes is a straightforward process that can be tackled with minor effort. As always, you're free to tweak all of the code samples shown in this tutorial. Doing so will surely help you grasp more quickly how to implement Polymorphism in PHP 5 using interfaces. Final thoughts That's all for the moment. In this introductory episode of the series, I demonstrated how easy and useful it is to implement Polymorphism in PHP 5 by way of interfaces. The driving force behind this approach is always Inheritance, even though, in this specific case, the previous "Div" class only inherits a set of generic methods. In the next tutorial I'm going to develop another sample application that will use the same "HtmlElement" interface that you saw before, but this time for building some HTML paragraphs. Don't miss the upcoming part!
blog comments powered by Disqus |
|
|
|
|
|
|
|