Polymorphism in PHP

Polymorphism in PHP describes a pattern in object oriented programming in which classes have different functionality while sharing a common interface.In other words its behave differently at different situation. In below example we are using calculatearea() to calculate different area.

It has two main content

  1. Overloading
  2. Overriding

Overloading is defining functions that have similar signatures, yet have different parameters. Overriding is only pertinent to derived classes, where the parent class has defined a method and the derived class wishes to override that method.

Overloading calculatearea()

<?php
interface Shape
{
public function calculatearea();
}
class Rectangle implements Shape
{ 
public $length; 
public $breadth; 
public __construct($l,$b) 
{ 
$this->$length=$l; $this->$breadth=$b;
 } 
public function calculatearea() 
{ 
return $this->$length*$this->$breadth;
 }
}
class Circle implements Shape
{ 
public $radius;
 public __construct($r)
 {
 $this->$radius=$r;
 }
 public function calculatearea()
 { 
return 3.14*$this->$radius*$this->$radius;
 }
}
$objR=new Rectangle(10,20);
echo $objR->calculatearea(); ///output will be 200
$objC=new Circle(20);
echo $objC->calculatearea(); ///output will be 1256
?>


Overriding myFunction() in class B
<?php

class A {
function myFunction()
 {
  return "A";
 }
}

class B extends A {
function myFunction() 
 {
  return "B";
 }
}

$a = new A;
$b = new B;
echo($a->myFunction()); //"A"
echo($b->myFunction()); //"B"
?>

Leave a Reply