Polymorphism in PHP: Mastering Object-Oriented Programming Techniques

Introduction

Greetings! In today's lesson, we'll unravel the concept of polymorphism in PHP's Object-Oriented Programming (OOP). Grasping polymorphism enables us to use a single entity (a method or class) to represent different types in various scenarios. Let's proceed.

Seeing Polymorphism in Action

Polymorphism, a pillar of OOP, allows one object to embody multiple forms. Visualize a button in software; depending on its type (for instance, a submit button or a radio button), the action resulting from pressing it varies. This dynamic encapsulates the spirit of polymorphism!

PHP supports polymorphism mainly through dynamic or run-time polymorphism, leveraging method overriding within abstract classes. Let's observe dynamic polymorphism in action within a simple application involving shapes. The base Shape class has an area method, which calculates the area for shapes. This method is uniquely implemented in the subclasses Rectangle and Circle.

<?php

abstract class Shape {
    // Abstract method for calculating area
    abstract public function area();
}

class Rectangle extends Shape {
    private $length;
    private $width;

    public function __construct($length, $width) {
        $this->length = $length;
        $this->width = $width;
    }

    // Override the abstract method to calculate rectangle area
    public function area() {
        return $this->length * $this->width;
    }
}

class Circle extends Shape {
    private $radius;

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

    // Override the abstract method to calculate circle area
    public function area() {
        return pi() * $this->radius * $this->radius;
    }
}

$rectangle = new Rectangle(2, 3);
echo $rectangle->area() . "\n"; // Prints: 6

$circle = new Circle(5);
echo $circle->area() . "\n"; // Prints: 78.539816339745

Here, polymorphism shines as the area() method takes on multiple forms while using the same Shape abstract class. It behaves differently depending on whether the object is a Rectangle or a Circle.

Using Polymorphism with an Array of Shapes

Polymorphism becomes particularly powerful when working with collections of objects, such as arrays. Let's see how it simplifies operations when dealing with an array of different shapes.

Imagine we want to calculate the total area of a group of shapes, which includes both rectangles and circles. With polymorphism, we can easily iterate over an array of Shape objects and calculate the area for each, regardless of its specific type.

<?php

$shapes = [
    new Rectangle(2, 3),
    new Circle(5),
    new Rectangle(4, 5)
];

$totalArea = 0;
foreach ($shapes as $shape) {
    $totalArea += $shape->area();
}

echo $totalArea; // Prints: 104.53981633974
Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal