This article explains what polymorphism is and how it applies to object oriented design in particular. It also explains the pros and cons of polymorphism when working with certain versions of PHP.
Continuing with our Person base class example, let’s take a look at a non-polymorphic implementation. The following example shows a really poor way to create an application that uses different types of Person objects. Note that the actual Person classes are omitted; we’re only concerned with the calling code for now.
This example shows objects that behave differently and a switch statement to differentiate between the different classes of Person, performing the correct operation on each. Note that the feedback comment in each condition is different. That probably would not be the case in a real application; it’s simply done to elucidate the differences in the class implementations.
Note the lack of the switch statement and, of greater importance, the lack of concern regarding what type of object Person::GetPerson() returned. Person::AddFeedback() is a polymorphic method. The behavior is one hundred percent encapsulated by the concrete class. Remember, whether we’re working with David, Charles or Alejandro, calling code never has to know the concrete class to function, only the base class.
While I’m sure there are better examples than mine, I think it demonstrates the basic use of polymorphism from the perspective of calling code. We now need to take into consideration the internals of the classes. One of the greatest aspects of inheriting from a base class is that the inheriting class is able to access the behaviors of the parent class, which often serve as nothing more than defaults, but can also be chained to inheriting methods to create more sophisticated behaviors. Below is a simple demonstration of this.
<?php class Person { function AddFeedback($comment, $sender, $date) { // Add feedback to database } }
class David extends Person { function AddFeedback($comment, $sender) { parent::AddFeedback($comment, $sender, date('Y-m-d')); } } ?>
Here we have chained the David::AddFeedback() method to the Person::AddFeedback method. You may note that it resembles overloaded methods in C++, Java, or C#. Remember that this is a simplified example, and that the actual code you write will of course be completely dependent on your project.