Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Explain Polymorphism in PHP.
Polymorphism is derived from the Greek words "Poly" (meaning many) and "morphism" (meaning forms). In object-oriented programming, polymorphism allows methods in different classes that perform similar functions to share the same interface, enabling code to work with objects of different classes through a common interface.
In PHP, polymorphism is implemented using interfaces or abstract classes. This ensures that different classes can be used interchangeably as long as they implement the same contract.
Using Interfaces for Polymorphism
An interface defines method signatures without implementation. Classes that implement an interface must provide implementations for all methods declared in the interface.
Example
Let's create a shape calculation system using polymorphism ?
<?php
interface Shape {
public function calculateArea();
}
class Circle implements Shape {
private $radius;
public function __construct($radius) {
$this->radius = $radius;
}
public function calculateArea() {
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 calculateArea() {
return $this->width * $this->height;
}
}
// Creating objects
$circle = new Circle(3);
$rectangle = new Rectangle(4, 5);
// Polymorphic behavior
echo "Circle area: " . $circle->calculateArea() . "<br>";
echo "Rectangle area: " . $rectangle->calculateArea() . "<br>";
// Function that works with any Shape
function printArea(Shape $shape) {
echo "Area: " . $shape->calculateArea() . "<br>";
}
printArea($circle);
printArea($rectangle);
?>
Circle area: 28.274333882308 Rectangle area: 20 Area: 28.274333882308 Area: 20
How It Works
The Shape interface defines a contract that all implementing classes must follow. Both Circle and Rectangle classes implement the calculateArea() method differently, but they can be used interchangeably through the common interface.
The printArea() function demonstrates polymorphism by accepting any object that implements the Shape interface, regardless of the specific class type.
Key Benefits
- Code Reusability: Functions can work with multiple object types
- Maintainability: Adding new shapes doesn't require changing existing code
- Flexibility: Objects can be treated uniformly through their interface
Conclusion
Polymorphism in PHP allows different classes to be used interchangeably through common interfaces or abstract classes. This promotes flexible, maintainable code where objects can be treated uniformly regardless of their specific implementation details.
