Polymorphism in PHP With Example
Let’s learn about Polymorphism in PHP.
Polymorphism is a fundamental concept in object-oriented programming (OOP) that allows objects of different classes to be treated as objects of a common base class.
Interfaces:
- PHP allows you to define interfaces, which are a set of method signatures that a class must implement.
- When a class implements an interface, it must provide concrete implementations for all the methods declared in the interface.
interface Shape {
public function calculateArea();
}
class Circle implements Shape {
private $radius;
public function __construct($radius) {
$this->radius = $radius;
}
public function calculateArea() {
return pi() * $this->radius * $this->radius;
}
}
class Square implements Shape {
private $side;
public function __construct($side) {
$this->side = $side;
}
public function calculateArea() {
return $this->side * $this->side;
}
}
$circle = new Circle(5);
echo $circle->calculateArea(); // Outputs the area of the circle
$square = new Square(4);
echo $square->calculateArea(); // Outputs the area of the square
Polymorphism allows you to write more flexible and reusable code by treating objects of different classes in a unified way, as long as they adhere to a common interface or share method names.
Abstract Class:
// Shape.php
abstract class Shape {
abstract public function calculateArea();
}
// Circle.php
class Circle extends Shape {
private $radius;
public function __construct($radius) {
$this->radius = $radius;
}
public function calculateArea() {
return pi() * $this->radius * $this->radius;
}
}
// Square.php
class Square extends Shape {
private $side;
public function __construct($side) {
$this->side = $side;
}
public function calculateArea() {
return $this->side * $this->side;
}
}
Now, let’s use polymorphism with these classes:
// Example usage in a controller or view
function printArea(Shape $shape) {
echo "Area: " . $shape->calculateArea() . PHP_EOL;
}
// Creating instances of Circle and Square
$circle = new Circle(5);
$square = new Square(4);
// Using polymorphism to calculate and print the area
printArea($circle); // Outputs the area of the circle
printArea($square); // Outputs the area of the square
In this example, the printArea
function takes a parameter of type Shape
, which is an abstract class. This function can accept any subclass of Shape
, such as Circle
or Square
, due to polymorphism. The calculateArea
method is called on the objects passed to printArea
, and the correct implementation (either from Circle
or Square
) is invoked based on the actual type of the object at runtime.
Hope you enjoyed!
Bonus: You must love my most read article : How To Use Single Responsibility Principle in PHP/Laravel
And most GitHub star repo:
https://github.com/mohasinhossain/SOLID-Principles-in-PHP