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.


<?php

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()
    {
        return $this->width * $this->height;
    }
}

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

Advertisements

One thought on “Polymorphism with PHP

Give your opinion

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s