PHP - Polymorphism

Polymorphism is a fundamental concept in object-oriented programming (OOP) that allows objects of different classes to be treated as instances of a common superclass. It enables you to write code that can work with objects in a generalized manner, without needing to know their specific classes. Polymorphism is achieved through method overriding and method overloading, and it's closely related to inheritance and interfaces. Here's how polymorphism works in advanced PHP programming:

Method Overriding:

Method overriding is the process of providing a new implementation for a method in a derived class that already exists in the base class. This allows you to customize the behavior of a method in the derived class.

class Shape {

    public function calculateArea() {

        return 0;

    }

}

class Circle extends Shape {

    private $radius;    

    public function __construct($radius) {

        $this->radius = $radius;

    }   

    public function calculateArea() {

        return pi() * $this->radius * $this->radius;

    }

}

class Rectangle extends Shape {

    private $width;

    private $height;

    public function __construct($width, $height) {

        $this->width = $width;

        $this->height = $height;

    }    

    public function calculateArea() {

        return $this->width * $this->height;

    }

}

In this example, both Circle and Rectangle classes override the calculateArea() method inherited from the Shape class. Each subclass provides its own implementation based on its specific behavior.

Interface Polymorphism:

Interfaces provide a way to achieve polymorphism by defining a contract that multiple classes can implement. This allows you to write code that works with objects based on their interface rather than their specific classes.

interface Logger {

    public function log($message);

}

class FileLogger implements Logger {

    public function log($message) {

        // Code to log message to a file

    }

}

class DatabaseLogger implements Logger {

    public function log($message) {

        // Code to log message to a database

    }

}

In this example, both FileLogger and DatabaseLogger implement the Logger interface. You can write code that works with any object that implements the Logger interface without needing to know the specific class.

The instanceof Operator:

You can use the instanceof operator to check if an object belongs to a specific class or implements a particular interface.

$logger = new FileLogger();

if ($logger instanceof Logger) {

    $logger->log("Log message");

}

Polymorphism allows you to write flexible and reusable code that can work with a variety of objects and classes. It's a key principle in OOP that promotes code modularity and maintainability.