Polymorphism in PHP
In this article I explain one of the oops feature in PHP or say Polymorphism.
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:
- Compile time (function overloading)
- 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
<?php
class Shap
{
function draw(){}
}
class Circle extends Shap
{
function draw()
{
print "Circle has been drawn.</br>";
}
}
class Triangle extends Shap
{
function draw()
{
print "Triangle has been drawn.</br>";
}
}
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();
}
?>
Output