Polymorphism in PHP

Introduction
 
Polymorphism is derived from two Greek words. Poly (meaning many) and morph (meaning forms). Polymorphism is one of the PHP Object Oriented Programming (OOP) features.  In general, polymorphism means the ability to have many forms. If we say it in other words, "Polymorphism describes a pattern in Object Oriented Programming in which a class has varying functionality while sharing a common interfaces.". There are two types of Polymorphism; they are: 
  1. Compile time (function overloading)
  2. Run time (function overriding)

But PHP "does not support" compile time polymorphism, which means function overloading and operator overloading.

Runtime Polymorphism
 
The Runtime polymorphism means that a decision is made at runtime (not compile time) or we can say we can have multiple subtype implements for a super class, function overloading is an example of runtime polymorphism . I will first describe function overloading. When we create a function in a derived class with the same signature (in other words a function has the same name, the same number of arguments and the same type of arguments) as a function in its parent class then it is called method overriding.
 
Example of runtime polymorphism in PHP
 
In the example given below we created one base class called Shap. We have inherit the Shap class in three derived classes and the class names are Circle, Triangle and Ellipse. Each class includes function draw to do runtime polymorphism. In the calling process, we have created an array of length 2 and each index of the array is used to create an object of one class. After that we use a loop that is executed for the length of the array and each value of $i is passed to the object array variable called $Val[$i]. So it is executed three times and it will call the draw() method of every class (but those classes have a draw method, whose object is previously created).
  1. <?php  
  2. class Shap  
  3. {  
  4. function draw(){}  
  5. }  
  6. class Circle extends Shap  
  7. {  
  8. function draw()  
  9. {  
  10. print "Circle has been drawn.</br>";  
  11. }  
  12. }  
  13. class Triangle extends Shap  
  14. {  
  15. function draw()  
  16. {  
  17. print "Triangle has been drawn.</br>";  
  18. }  
  19. }  
  20. class Ellipse extends Shap  
  21. {  
  22. function draw()  
  23. {  
  24. print "Ellipse has been drawn.";  
  25. }  
  26. }  
  27.    
  28. $Val=array(2);  
  29.   
  30. $Val[0]=new Circle();  
  31. $Val[1]=new Triangle();  
  32. $Val[2]=new Ellipse();  
  33.   
  34. for($i=0;$i<3;$i++)  
  35. {  
  36. $Val[$i]->draw();  
  37. }  
  38. ?>  
Output

overriding-in-php.jpg

Up Next
    Ebook Download
    View all
    Learn
    View all