Building Polymorphs in PHP 5

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.

If you’ve ever developed applications with C, then you know that its support for Polymorphism is thorough, clear and well defined. Being a structured, strictly-typed language, C will let you define functions that have the same name and that also accept the same number of arguments. However, if the arguments taken by one function aren’t of the same type as the ones taken by another, then it’s assumed that these are different functions that will behave differently as well.

In the case of C, Polymorphism is achieved due to the strict nature of the language itself, which bring to us, as passionate PHP developers, an interesting question: if PHP is a weakly-typed language where functions are remarkably permissive regarding the arguments that they can accept (for good or for bad), how can Polymorphism be successfully achieved, then?

Well, since at the function level Polymorphism simply can’t be implemented for the reasons that I gave before, it can be easily achieved at class level instead. Let me clarify this concept: if there are two classes that inherit a certain method from the same parent, but each of them give it a different implementation, then the objects derived from those classes will be considered polymorphs.

Essentially, in the case of PHP, Polymorphism is implemented through Inheritance. This concept can be taken even further with PHP 5, since it supports not only creating parent classes in a traditional way, but defining interfaces as well. Since one class can inherit methods from a base class, one or many interfaces, or both, PHP 5 provides developers with the ability to implement Polymorphism via regular Inheritance or via interfaces.

Definitely, this capability of PHP 5 to construct polymorphs using two different approaches can be really useful for developing object-oriented applications that exploit code reuse in a more efficient manner. Thus, in this set of articles I’m going to take a close look at achieving Polymorphism in PHP 5 through interfaces, and through the use of parent classes, so you can easily spot the differences between these two methodologies, and evaluate their pros and cons.

Now, it’s time to get rid of the dull theory and start building polymorphs using PHP 5 interfaces. Let’s go!

{mospagebreak title=Implementing Polymorphism via interfaces: working with HTML element objects}

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:

interface HtmlElement

{

// 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.

{mospagebreak title=Implementing the HtmlElement interface: building a div element class}

Now that I’ve defined a basic interface with the bare bones structure of a generic HTML element, it’s time create a class that implements the set of methods declared by this interface. As you’ll see in a moment, these methods will allow it to build polymorph objects very easily.

That being explained, here’s the implementer class of the previous "HtmlElement" interface. Its function is to construct basic divs. Take a look at the partial source code of this class, please:

class Div implements HtmlElement

{

private $id = ‘divid';

private $class = ‘divclass';

private $content = ‘Default content for the div';

 

 // assign id attribute to div element

public function setId($id = ”)

{

if ($id !== ”)

{

$this->id = $id;

}

return $this;

}

 

// assign class attribute to div element

public function setClass($class = ”)

{

if ($class !== ”)

{

$this->class = $class;

}

return $this;

}

}

As depicted above, the new "Div" class gives a concrete implementation to the "setId()" and "setClass()" methods defined at the top of the hierarchy, a process that demonstrates in a nutshell how to take advantage of Polymorphism in PHP 5 by using a simple interface.

However, as you may know, when a class implements an interface, it must do this with all of the interface’s methods. That isn’t the case with the above "Div" class, since no logic has been added yet to the "setContent()" and render()" methods.

Obviously, it’s necessary to address this issue as soon as possible. Therefore, below I’ve included the complete definition of the "Div" class, this time implementing the aforementioned methods. Here it is:

class Div implements HtmlElement

{

private $id = ‘divid';

private $class = ‘divclass';

private $content = ‘Default content for the div';

 

 // assign id attribute to div element

public function setId($id = ”)

{

if ($id !== ”)

{

$this->id = $id;

}

return $this;

}

 

// assign class attribute to div element

public function setClass($class = ”)

{

if ($class !== ”)

{

$this->class = $class;

}

return $this;

}

 

// set content for div element

public function setContent($content = ”)

{

if ($content !== ”)

{

$this->content = $content;

}

return $this;

}

 

// render div element

public function render()

{

return ‘<div id="’ . $this->id . ‘" class="’ . $this->class . ‘">’ . $this->content . ‘</div>';

 

}

}  

Certainly, you’ll have to agree with me that the definition of the "Div" class now looks much clearer. The corresponding "setContent()" and "render()" methods have been specifically implemented to construct an HTML div element.

Despite the simplicity of this sample class, it’s useful for showing how easy it is to build polymorph classes in PHP 5 by inheriting the set of methods declared by a certain interface.

So far, so good. Now that you’ve hopefully grasped the underlying logic of the earlier "Div" class, I’m going to set up an example that demonstrates the actual functionality of the class.

Bearing that idea in mind, in the following section I’m going to develop that example for you, which will be an adequate conclusion for this first part of the series.

Now read the next segment. I’ll be there, waiting for you.

{mospagebreak title=Creating an HTML div in a few simple steps}

As I promised in the previous segment, below I wrote a script that shows how to use the polymorph "Div" class to display a containing div on screen. Here’s the corresponding code fragment:

// create new instance of Div class

$div = new Div();

// assign attributes and content for div element and display it on the browser

$div->setId(‘myid’);

$div->setClass(‘myclass’);

$div->setContent(‘This is the new content for the div.’);

echo $div->render();

 

That was easy to code, wasn’t it? Due to the intuitive API of the "Div" class, it’s really simple to create first an instance of it, then assign some trivial values to its properties via the pertinent setter methods, and finally render the div element on screen.

In addition, since most of the methods of this class are chainable, it’s feasible to rewrite the previous script a little bit more tightly, like this:

// create new instance of Div class

$div = new Div();

// assign attributes and content for div element and display it on the browser

echo $div->setId(‘myid’)

->setClass(‘myclass’)

->setContent(‘This is the new content for the div.’)

->render();

There you have it. Thanks to the neat support offered by PHP 5 for working with interfaces, building polymorph classes is a straightforward process that can be tackled with minor effort.

As always, you’re free to tweak all of the code samples shown in this tutorial. Doing so will surely help you grasp more quickly how to implement Polymorphism in PHP 5 using interfaces.

Final thoughts

That’s all for the moment. In this introductory episode of the series, I demonstrated how easy and useful it is to implement Polymorphism in PHP 5 by way of interfaces. The driving force behind this approach is always Inheritance, even though, in this specific case, the previous "Div" class only inherits a set of generic methods.

In the next tutorial I’m going to develop another sample application that will use the same "HtmlElement" interface that you saw before, but this time for building some HTML paragraphs.

Don’t miss the upcoming part!

[gp-comments width="770" linklove="off" ]
antalya escort bayan antalya escort bayan