Building Dynamic Web Pages with Polymorphism in PHP 5 - Extending the concept of polymorphic classes (
Page 3 of 4 )
In accordance with the concepts that were deployed in the previous section, after creating the corresponding classes that display some (X)HTML headers, the next step that I'm going to take now involves deriving some additional subclasses from the parent "WebPageElement." These will be responsible for rendering different web page elements, in this case including paragraphs, divs and some regular links.
The respective signatures for these classes are listed below, so I suggest you take a look at them:
// define concrete 'Paragraph' class
class Paragraph extends WebPageElement{
public function __construct($data,$id,$class){
parent::__construct($data,$id,$class);
}
public function display(){
$html='<p';
if(!empty($this->id)){
$html.=' id="'.$this->id.'"';
}
if(!empty($this->class)){
$html.=' class="'.$this->class.'"';
}
$html.='>'.$this->data.'</p>';
return $html;
}
}
// define concrete 'Div' class
class Div extends WebPageElement{
public function __construct($data,$id,$class){
parent::__construct($data,$id,$class);
}
public function display(){
$html='<div';
if(!empty($this->id)){
$html.=' id="'.$this->id.'"';
}
if(!empty($this->class)){
$html.=' class="'.$this->class.'"';
}
$html.='>'.$this->data.'</div>';
return $html;
}
}
// define concrete 'Link' class
class Link extends WebPageElement{
private $href;
public function __construct($data,$id,$class,$href){
parent::__construct($data,$id,$class);
$this->href=!empty($href)?$href:'#';
}
public function display(){
$html='<a';
if(!empty($this->id)){
$html.=' id="'.$this->id.'"';
}
if(!empty($this->class)){
$html.=' class="'.$this->class.'"';
}
$html.=' href="'.$this->href.'">'.$this->data.'</a>';
return $html;
}
}
As you can see, the three classes listed above look closely similar to the ones shown in the previous section. However, these are tasked with displaying paragraphs, divs and regular links, and they all implement its "display()" method differently. Again, I'm working with polymorphic objects. Pretty simple, isn't it?
All right, at this stage I already defined a decent number of subclasses whose purpose is simply displaying web page elements, meaning that it's possible to use them to create a complete web document. Of course, the best point of all is that this process can be achieved by taking advantage of polymorphism.
In the next section I'm going to set up an illustrative example to show you clearly how a simple web page can be generated by using all the classes that I built previously.
To learn how this practical example will be developed, please click on the link that appears below and keep reading.