Current Location: Home> Latest Articles> PHP Polymorphism Explained with Practical Examples

PHP Polymorphism Explained with Practical Examples

M66 2025-10-16

Understanding Polymorphism in PHP

In object-oriented programming, polymorphism refers to the ability of different objects to respond differently to the same message. In PHP, polymorphism is mainly achieved through interfaces and inheritance. In this article, we will explore PHP polymorphism with practical code examples.

Defining the Shape Interface

First, we create an interface Shape, which contains a calculateArea method:

interface Shape {
    public function calculateArea();
}

Implementing Circle and Square Classes

Next, we create two classes, Circle and Square, both implementing the Shape interface:

class Circle implements Shape {
    private $radius;

    public function __construct($radius) {
        $this->radius = $radius;
    }

    public function calculateArea() {
        return round(pi() * pow($this->radius, 2), 2);
    }
}

class Square implements Shape {
    private $sideLength;

    public function __construct($sideLength) {
        $this->sideLength = $sideLength;
    }

    public function calculateArea() {
        return pow($this->sideLength, 2);
    }
}

Creating a Polymorphic Function getShapeArea

Then, we define a function getShapeArea, which accepts an object implementing the Shape interface and calls its calculateArea method:

function getShapeArea(Shape $shape) {
    return $shape->calculateArea();
}

Usage Example

Now, we can create Circle and Square objects and use the getShapeArea function to calculate their areas:

$circle = new Circle(5);
$square = new Square(4);

echo "Circle area: " . getShapeArea($circle) . ";";
echo "Square area: " . getShapeArea($square) . ".";

In this example, the Circle and Square classes both implement the Shape interface and override the calculateArea method. By passing different objects into the getShapeArea function, we achieve polymorphism: the same function executes different logic based on the object type.

Conclusion

Polymorphism in PHP, achieved through interfaces and inheritance, allows different objects to respond differently to the same message. This mechanism enhances code flexibility and scalability. Proper use of polymorphism can simplify code structure, improve code reuse, and make object-oriented programs more maintainable.