Implementing Polymorphism via interfaces: working with HTML element objects - PHP
You don't need to be working in a strictly-typed language like C to enjoy the benefits of polymorphism. You just need to achieve it at a different level. In this seven-part series, you'll learn how to use polymorphism in PHP 5.
Since the purpose of this introductory part of the series is to demonstrate how to implement Polymorphism in PHP 5 by means of interfaces, I'm first going to define a simple interface that will declare some generic methods for outlining the general structure and behavior of an HTML containing element.
Once you've seen the structure of this interface, I'll move on and code a new class that will implement all of its methods. That being said, here's the definition of the interface, which not surprisingly is called "HtmlElement." Check it out:
// assign id attribute to HTML element
public function setId($id = '');
// assign class attribute to HTML element
public function setClass($class = '');
// set content for HTML element
public function setContent($content = '');
// render HTML element
public function render();
Certainly, it's easy to understand the rationale behind the above interface. As you can see, it declares only three public methods. The first two assign "id" and "class" attributes to a generic HTML element, and the last one can be used for displaying that element on the browser.
So far, there's nothing special about the way that this interface has been defined, right? However, here's where things become really interesting; the next step to taking advantage of Polymorphism is to create an implementer of the interface that specifically constructs a div element.
So, if you wish to learn the full details of how this new class will be created, then click on the link displayed below and read the section to come.