Understanding and Applying Polymorphism in PHP
What is Polymorphism?
Polymorphism is derived from two Greek words. Poly (meaning many) and morph (meaning forms). Polymorphism means many forms.
An integral part of polymorphism is the common interface. There are two ways to define an interface in PHP: interfaces and abstract classes. Both have their uses, and you can mix and match them as you see fit in your class hierarchy.
Interfaces
An interface is similar to a class except that it cannot contain code. An interface can define method names and arguments, but not the contents of the methods. Any classes implementing an interface must implement all methods defined by the interface. A class can implement multiple interfaces.
Example
<?php
interface IShape{
public function getArea();
public function getPerimeter();
}
class Rectangle implements IShape{
private $width;
private $height;
public function __construct($w,$h){
$this->width=$w;
$this->height=$h;
}
public function getArea(){
return $this->width*$this->height;
}
public function getPerimeter(){
return 2*($this->width+$this->height);
}
}// end Rectangle class
class Circle implements IShape{
private $radii;
const PI=3.145;
public function __construct($r){
$this->radii=$r;
}
public function getArea(){
return Circle::PI*$this->radii*$this->radii;
}
public function getPerimeter(){
return 2*Circle::PI*$this->radii;
}
}// end Circle class
class Triangle implements IShape{
private $side_a;
private $side_b;
private $side_c;
public function Triangle($a,$b,$c){
$this->side_a=$a;
$this->side_b=$b;
$this->side_c=$c;
}
public function getArea(){
$p=($this->side_a+$this->side_b+$this->side_c) /2;
return sqrt($p*($p-$this->side_a)*($p-$this->side_b)*($p-$this->side_c));
}
public function getPerimeter(){
return $this->side_a+$this->side_b+$this->side_c;
}
} //end Triangle class
//---------------------Util-----------------------//
function getShapeArea(IShape $obj){
echo "Area: ".$obj->getArea()."<br/>";
}
function getShapePerimeter(IShape $obj){
echo "Perimeter: ".$obj->getPerimeter()."<br/>";
}
//---------------------Use------------------------
echo "<strong>Rectangle</strong>";
$rect=new Rectangle(9,5);
getShapeArea($rect);
getShapePerimeter($rect);
echo "<strong>Circle</strong>";
$circle=new Circle(9);
getShapeArea($circle);
getShapePerimeter($circle);
echo "<strong>Triangle</strong>";
$tri=new Triangle(8,7,5);
getShapeArea($tri);
getShapePerimeter($tri);
?>
Output
Rectangle
Area: 45
Perimeter: 28
Circle
Area: 254.745
Perimeter: 56.61
Triangle
Area: 17.320508075689
Perimeter: 20
Comments 4