As I said in the section that you just read, it'd be pretty instructive to develop an example that depicts how to use the "HtmlElement" interface shown before for building a polymorph class that renders HTML paragraphs instead of plain divs. The purpose of this example is to illustrate how two classes that implement the same interface can reveal different behavior, even when they have the same methods. But wait a minute! Doesn't this sound like the definition of polymorph objects in PHP 5? Of course it does. And to demonstrate this concept more clearly, below I included the definition of the class that will display the aforementioned HTML paragraphs on the browser. Study its definition, please: class Paragraph implements HtmlElement { private $id = 'parid'; private $class = 'parclass'; private $content = 'Default content for the paragraph';
// assign id attribute to paragraph element public function setId($id = '') { if ($id !== '') { $this->id = $id; } return $this; }
// assign class attribute to paragraph element public function setClass($class = '') { if ($class !== '') { $this->class = $class; } return $this; }
// set content for paragraph element public function setContent($content = '') { if ($content !== '') { $this->content = $content; } return $this; }
// render paragraph element public function render() { return '<p id="' . $this->id . '" class="' . $this->class . '">' . $this->content . '</p>';
} } As you can see, the signature of the whole new "Paragraph" class looks quite similar to the one that constructs div elements, except for some subtle differences, such as the default values assigned to its properties and the definition of its "render()" method. Logically, this must be that way, because the class renders paragraphs and not divs. This demonstrates that two or more classes that implement the same interface can act completely differently when their homonymous methods are invoked in exactly the same context. Simply studying the signature of the previous "Paragraph" class should be enough to let you grasp the underlying logic behind building polymorph objects via interfaces. But if you still have some doubts about this topic, in the section to come I'm going to create a short script that will display an HTML paragraph on the browser. To see how this script will be coded, read the next few lines.
blog comments powered by Disqus |
|
|
|
|
|
|
|