Friday, January 8, 2016

Implementation of Polymorphism


Polymorphism is derived from two Greek words. Poly (meaning many) and morph (meaning forms). Polymorphism means many forms. In C you have two methods with the same name that have different function signatures and hence by passing the correct function signature you can invoke the correct method.

This is how polymorphism is achieved in languages like C where in a function sum(int, int) differs from sum(float, float). Therefore the method sum() has many forms depending on the parameters being passed to it.

The meaning with Object Oriented languages changes. With Object Oriented language polymorphism happens:

When the decision to invoke a function call is made by inspecting the object at runtime it is called Polymorphism


PHP 5 Polymorphism


Since PHP 5 introduces the concept of Type Hinting, polymorphism is possible with class methods. The basis of polymorphism is Inheritance and overridden methods.

Lets look at an example:
 
class BaseClass {
   public function myMethod() 
    {
      echo "BaseClass method called";
    }
}
 
class DerivedClass extends BaseClass 
    {
   public function myMethod() {
      echo "DerivedClass method called";
    }
}
 
function processClass(BaseClass $a) {
   $a->myMethod();
}
 
$a = new DerivedClass();
processClass($a);


In this code object $a of class DerievedClass is executed and passed to the processClass() method. The parameter accepted in processClass() is that of BaseClass, within in processClass() the method myMethod() is being called Since the method is being called on the class variable of BaseClass. 






















Share this

0 Comment to "Implementation of Polymorphism"

Post a Comment