PHP Page 3 - Polymorphs in PHP: Using Interfaces and Abstract Classes to Construct HTML Paragraphs |
As I explained in the preceding section, to demonstrate that it’s possible to construct polymorph objects by combining the functionality of interfaces and abstract class, I"m going to derive a new child class from the parent “HtmlElement,” which also will be an implementer of the “Parser” interface. Here’s the definition of the new subclass, whose function is to render HTML paragraphs: // define Paragraph class (subclass of HtmlElement class) class Paragraph extends HtmlElement { public function parseContent() { if ($this->content !== '') { $this->content = str_replace(array('</p>','</p>)'), "", $this->content);
} return $this; } // render paragraph element public function render() { return '<p id="' . $this->id . '" class="' . $this->class . '">' . $this->content . '</p>';
} } Didn’t I tell you that building a polymorph class by using interfaces and abstract classes was a straightforward process? Well, if you pay close attention to the above “Paragraph” class, then you’ll realize that I was right. Obviously, aside from inheriting all of the methods defined by its corresponding parent, this child class gives concrete implementation to the “parseContent()” method declared within the “Parser” interface. Nonetheless, this time the method will remove any “<p></p>” tags included in the contents of the HTML paragraphs being constructed. Do you see how simple it is to make two classes that belong to the same family and implement the same interface behave entirely differently? I guess you do. However, to dissipate any doubts that you might have on this topic, in the last segment of this tutorial I’m going to set up an example that will show how to work with the previous “Paragraph” class. Therefore, to see how this final example will be developed, read the following section. I’ll be there, waiting for you.
blog comments powered by Disqus |
|
|
|
|
|
|
|