Polymorphism is a long word for a very simple concept. Polymorphism describes a pattern in object-oriented programming in which classes have different functionality while sharing a common interface. In the programming world, polymorphism is used to make applications more modular and extensible
The provision of a single interface to entities of different types. Basically it means PHP is able to process objects differently depending on their data type or class. This powerful feature allows you to write interchangeable objects that sharing the same interface.
<?php
interface Shape {
public function name();
}
class Circle implements Shape {
public function name() {
echo "I am a circle";
}
}
class Triangle implements Shape {
public function name() {
echo "I am a triangle";
}
}
function test(Shape $shape) {
$shape->name();
}
test(new Circle()); // I am a circle
test(new Triangle()); // I am a triangle
?>
Above example, test(Shape $shape) function declares(type hints) its only parameter to be Shape type. This function is not aware of Circle and Triangle classes. When either class is passed to this function as a parameter, it processes respectively.
<?php
interface Shape {
public function getArea();
}
class Square implements Shape {
private $width;
private $height;
public function __construct($width, $height) {
$this->width = $width;
$this->height = $height;
}
public function getArea(){
return $this->width * $this->height;
}
}
class Circle implements Shape {
private $radius;
public function __construct($radius) {
$this->radius = $radius;
}
public function getArea(){
return 3.14 * $this->radius * $this->radius;
}
}
function calculateArea(Shape $shape) {
return $shape->getArea();
}
$square = new Square(8, 8);
$circle = new Circle(7);
echo calculateArea($square), "<br/>";
echo calculateArea($circle);
?>
© 2025 Easy To Learning. All Rights Reserved | Design by Easy To Learning