In the earlier section I defined a simple interface in conjunction with the “HtmlElement” abstract class, so next I'll build a subclass that implements the interface. Want to see how this can be accomplished in a single step? Look at the following code sample, which redefines the “Div” class that you saw before: class Div extends HtmlElement implements Parser { public function parseContent() { if ($this->content !== '') { $this->content = preg_replace(array('/(<html>|<body>)/', '/(</html>|</body>)/'), array('<div>', '</div>'), $this->content); } return $this; } // render div element public function render() { return '<div id="' . $this->id . '" class="' . $this->class . '">' . $this->content . '</div>';
} } By examining the definition of the improved “Div” class, you can see how easy it is to build polymorph objects that inherit structure and functionality from an interface and an abstract class. Please, notice how this concrete class implements the inherited “parseContent()” method to replace some invalid tags with divs, thus basically sanitizing its contents. Now that you've grasped the driving logic of the previous class, it’s time to see how it can be used for displaying a single div on the browser. The following script shows how to do that:
// 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('divid') ->setClass('divclass') ->setContent('<html>This is the new content for the div.</html>') ->parseContent() ->render(); Here you have it. With this basic example I showed that constructing polymorph classes that inherit methods from an abstract class and one or more interfaces is indeed a straightforward process. As usual, feel free to tweak all of the code samples included in this tutorial, so you can sharpen your Polymorphism skills in PHP 5. Final thoughts This is it for the moment. Over the course of this fifth chapter of the series, you learned how to build a polymorph object in PHP 5 by combining an abstract class and a simple interface, which was useful for constructing basic HTML divs. In the next tutorial I’m going to show you how to construct a polymorph class using the previous approach, but this time the class will be responsible for rendering HTML paragraphs. Don’t miss the upcoming article!
blog comments powered by Disqus |
|
|
|
|
|
|
|