Polymorphism with PHP

What is Polymorphism?

The general definition is this: The ability of an object to exist in various forms.
In particular with programming the term is this: Polymorphism describes a pattern in object oriented programming in which classes have different functionality while sharing a common interface.


interface Shape
    public function calcArea();

class Circle implements Shape
    private $radius;

    public function __construct($radius)
        $this->radius = $radius;

    public function calcArea()
        return $this->radius * $this->radius * pi();

class Rectangle implements Shape
    private $width;
    private $height;

    public function __construct($width, $height)
        $this->width  = $width;
        $this->height = $height;

    public function calcArea()

$circ = new Circle(2);
$rect = new Rectangle(3,4);

echo $circ->calcArea();
echo '
echo $rect->calcArea();

// 12.566370614359
// 12

And this is it. The Circle and the Rectangle share the same interface, but their formulas for calculating the object areas are totally different.


One thought on “Polymorphism with PHP

Give your opinion


WordPress.com Logo


Twitter picture


Facebook photo


Google+ photo


Connecting to %s