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.

Published by T3at1m3

PHP Developer

Join the Conversation

1 Comment

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.