What is Polymorphism in PHP: Simple Explanation and Example
polymorphism means that different classes can have methods with the same name but different behaviors. It allows you to use a single interface or parent class to work with different types of objects, making your code flexible and easier to extend.How It Works
Polymorphism in PHP works like a universal remote control that can operate many different devices, each responding in its own way. Imagine you have a remote (the interface or parent class) and several devices (child classes). When you press a button (call a method), each device reacts differently but understands the command.
This happens because child classes can have their own version of a method defined in a parent class or interface. When you call that method on an object, PHP decides which version to run based on the object's actual class. This lets you write code that works with many types of objects without knowing their exact class in advance.
Example
This example shows two classes, Dog and Cat, both having a speak() method. We use a function that accepts any animal and calls speak(), demonstrating polymorphism.
<?php
interface Animal {
public function speak();
}
class Dog implements Animal {
public function speak() {
return "Woof!";
}
}
class Cat implements Animal {
public function speak() {
return "Meow!";
}
}
function animalSound(Animal $animal) {
echo $animal->speak() . "\n";
}
$dog = new Dog();
$cat = new Cat();
animalSound($dog); // Woof!
animalSound($cat); // Meow!
When to Use
Use polymorphism when you want to write code that can work with different types of objects in a uniform way. It is especially useful in large programs where you might add new types later without changing existing code.
For example, in a game, you might have many characters like players, enemies, and NPCs. Each can have a move() method, but they move differently. Polymorphism lets you call move() on any character without worrying about the details.
Key Points
- Polymorphism allows methods with the same name to behave differently in different classes.
- It relies on interfaces or parent classes to define common method names.
- It helps make code flexible, reusable, and easier to maintain.
- PHP supports polymorphism through interfaces and class inheritance.