Polymorphism is a fundamental concept in object-oriented programming (OOP) that allows objects of different classes to be treated as objects of a common superclass. In PHP, polymorphism is achieved through method overriding and method overloading. It enables you to write code that can work with objects of different classes in a consistent manner.

 

Method Overriding:

Method overriding occurs when a subclass provides a different implementation of a method that is already defined in its superclass. The overridden method in the subclass must have the same name, return type, and compatible parameters as the method in the superclass. Here's an example:

class Animal {
    public function makeSound() {
        echo "The animal makes a sound.";
    }
}

class Cat extends Animal {
    public function makeSound() {
        echo "Meow!";
    }
}

class Dog extends Animal {
    public function makeSound() {
        echo "Woof!";
    }
}

$animal = new Animal();
$cat = new Cat();
$dog = new Dog();

$animal->makeSound();  // Output: The animal makes a sound.
$cat->makeSound();     // Output: Meow!
$dog->makeSound();     // Output: Woof!

In this example, the Animal class defines a makeSound() method. The Cat and Dog classes inherit from Animal and override the makeSound() method with their own implementations. When calling makeSound() on an object, the appropriate implementation is invoked based on the actual type of the object.

Method Overloading.

Method overloading refers to having multiple methods in a class with the same name but different parameters. PHP doesn't support method overloading directly, but you can simulate it using the __call() magic method or by utilizing conditional logic inside a method. Here's an example using conditional logic:

class Math {
    public function calculate($x, $y) {
        return $x + $y;
    }

    public function calculate($x, $y, $z) {
        return $x + $y + $z;
    }
}

$math = new Math();

echo $math->calculate(2, 3);        // Output: 5
echo $math->calculate(2, 3, 4);     // Output: 9

In this example, the Math class has two calculate() methods—one that takes two parameters and another that takes three parameters. Depending on the number of arguments provided, the appropriate calculate() method is invoked.

Polymorphism allows you to write generic code that can operate on objects of different classes as long as they share a common interface or superclass. It promotes code reuse, extensibility, and flexibility in OOP systems.