Since my plan here consists of demonstrating how to construct polymorph objects by combining interfaces and abstract classes together, I’m going to reuse the “HtmlElement” class that you saw in the previous segment, along with a brand new interface called “Parser.” Later on, these entities will be used again for constructing more complex HTML elements. Having explained my goal, it’s example time. So, here’s the trivial definition of the “Parser” interface, along with the corresponding “HtmlElement” class:
// define interface Parser interface Parser { public function parseContent(); }
// define abstract class HtmlElement abstract class HtmlElement { protected $id = 'myid'; protected $class = 'myclass'; protected $content = 'Default content for the HTML element';
// assign id attribute to HTML element public function setId($id = '') { if ($id !== '') { $this->id = $id; } return $this; }
// assign class attribute to HTML element public function setClass($class = '') { if ($class !== '') { $this->class = $class; } return $this; }
// set content for HTML element public function setContent($content = '') { if ($content !== '') { $this->content = $content; } return $this; }
// render HTML element (not implemented) abstract function render(); } Since the purpose of the “Parser()” interface is to provide structure to any HTML element, and the abstract class adds logic to that element, there’s nothing special to note with reference to the previous code fragment. However, it’s valid to say that if I derive a subclass from the base “HtmlElement” that also implements the “Parser()” interface, this child would be inheriting both structure and logic, right? This could be useful if you want to specify different behaviors for diverse HTML element objects when their inherited “parseContent()” method gets invoked. Let me clarify this concept, so you can grasp it more easily: the “Div” class built in the previous section could implement the “parseContent()” method to replace certain incorrect tags, such as “<html> and “<body”>, with “<div>” tags when assigning its contents. Its sister “Paragraph” could do something similar, but in that case it’d simply remove nested paragraphs. Well, if this explanation still sounds a bit confusing to you, fear not; in the last section of this tutorial I’m going to show you how to redefine the previous “Div” class so it can engage in the aforementioned polymorph behavior. Now, read the upcoming segment. We’re almost finished!
blog comments powered by Disqus |
|
|
|
|
|
|
|