loading...

Polymorphism In PHP

pakainfocom profile image pakainfo ・2 min read

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

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

 
class Shap  
{  
function draw(){}  
}  
class Circle extends Shap  
{  
function draw()  
{  
print "Circle has been drawn.";  
}  
}  
class Triangle extends Shap  
{  
function draw()  
{  
print "Triangle has been drawn.";  
}  
}  
class Ellipse extends Shap  
{  
function draw()  
{  
print "Ellipse has been drawn.";  
}  
}  
   
$Val=array(2);  
  
$Val[0]=new Circle();  
$Val[1]=new Triangle();  
$Val[2]=new Ellipse();  
  
for($i=0;$i<3;$i++)  
{  
$Val[$i]->draw();  
}   

also you can more Example with demo : Click Here

Posted on by:

pakainfocom profile

pakainfo

@pakainfocom

My name is Angular King. I'm a full-stack developer, entrepreneur and owner of Pakainfo. I live in India and I love to write

Discussion

pic
Editor guide