Polymorphism in PHP
Polymorphism in PHP is a concept from object-oriented programming that lets us perform a single action in different ways. It's like a coffee machine that can make different types of coffee from the same set of buttons. In PHP, polymorphism allows objects from different classes to be treated as objects of a common parent class.
The magic of polymorphism is that it lets us use one interface for many forms of data. For instance, if you have a function that expects a 'Shape' object, you can pass it any specific shape like 'Circle', 'Square', or 'Triangle', as long as they are derived from the 'Shape' class. This makes the function more versatile and your code more flexible.
PHP implements polymorphism primarily through interfaces and abstract classes. Both of these provide a structure that other classes can follow, ensuring they include specific methods. The difference is that while interfaces only declare methods without implementing them, abstract classes can provide some implementation.
Runtime Polymorphism
Runtime polymorphism is a concept where the decision about which method to execute is made at runtime. Imagine you have a remote control for playing various games. The button you press decides the game to play, but this decision happens when you press the button, not when you set up the remote. In PHP, this is often seen with method overriding, where a method in a subclass has the same name and structure as a method in its parent class but does a different job.
Let's look at a simple example to understand this better. Suppose we have a class called Animal with a method makeSound(). We can have other classes like Dog and Cat that extend Animal and override the makeSound() method to produce sounds specific to each animal.
PHP
<?php
class Animal {
public function makeSound() {
echo "Some sound";
}
}
class Dog extends Animal {
public function makeSound() {
echo "Bark";
}
}
class Cat extends Animal {
public function makeSound() {
echo "Meow";
}
}
// Create a Dog object
$myDog = new Dog();
$myDog->makeSound();
// Create a Cat object
$myCat = new Cat();
$myCat->makeSound();
?>
Outputs:
Bark
Meow
In this example, even though we call makeSound() on both Dog and Cat objects, the actual sound made depends on the type of object, and this decision is made at runtime.
Types of PHP Polymorphism
In PHP, polymorphism can mainly be achieved in two ways: using interfaces and using abstract classes. Both methods provide a way to enforce certain methods to be implemented by multiple classes.
Example 1:
Polymorphism using Interface
An interface is like a contract for a class. It tells the class, "If you agree to this contract, you must provide these specific methods." Interfaces don't have any actual code in them; they just define method names and parameters. Classes that implement an interface must provide implementations for all of the interface's methods.
Here's a simple example:
PHP
<?php
interface Shape {
public function draw();
}
class Circle implements Shape {
public function draw() {
echo "Drawing a circle";
}
}
class Square implements Shape {
public function draw() {
echo "Drawing a square";
}
}
$myCircle = new Circle();
$myCircle->draw();
$mySquare = new Square();
$mySquare->draw();
?>
Output
Drawing a circle
Drawing a square
In this example, both Circle and Square classes implement the Shape interface and provide their own version of the draw() method.
Polymorphism using Abstract Classes
An abstract class is like a partial blueprint for other classes. It can have some methods with actual code and some methods that are just declared (without implementation). If a class extends an abstract class, it must implement all of the abstract class's declared methods.
Here's how it might look:
PHP
<?php
abstract class Animal {
public function sleep() {
echo "Sleeping";
}
abstract public function makeSound();
}
class Dog extends Animal {
public function makeSound() {
echo "Bark";
}
}
$myDog = new Dog();
$myDog->sleep();
$myDog->makeSound();
?>
Outputs:
Sleeping
Bark
In this example, Animal is an abstract class with a concrete method sleep() and an abstract method makeSound(). The Dog class, which extends Animal, provides an implementation for the makeSound() method.
Understanding these two types of polymorphism helps in designing flexible and reusable code in PHP.
Example 2:
Polymorphism using Interface
Using an interface in PHP is a way to make sure certain classes all include the same functions, but each class can have its own version of these functions. It's like saying, "Hey, if you want to be part of this group, you need to be able to do these things, but you can do them your way."
Let's see an example with shapes again, but this time focusing on calculating the area.
PHP
<?php
interface Shape {
public function calcArea();
}
class Circle implements Shape {
private $radius;
public function __construct($radius) {
$this->radius = $radius;
}
public function calcArea() {
return pi() * $this->radius * $this->radius;
}
}
class Rectangle implements Shape {
private $width;
private $height;
public function __construct($width, $height) {
$this->width = $width;
$this->height = $height;
}
public function calcArea() {
return $this->width * $this->height;
}
}
$circle = new Circle(5);
echo "Circle area: " . $circle->calcArea() . "<br>";
$rectangle = new Rectangle(4, 5);
echo "Rectangle area: " . $rectangle->calcArea();
?>
Output
the area of the circle
the area of the rectangle
In this code, both Circle and Rectangle classes implement the Shape interface. This means they both must have a calcArea function. For a circle, the area is calculated using πr², and for a rectangle, it's width * height. This shows polymorphism because the same function calcArea is used to calculate the area, but the way it's calculated depends on the shape.
Polymorphism using Abstract Classes
Abstract classes are a bit like incomplete templates. They say, "Here's what you need to do, but I'll let you fill in the details." They can have some methods already filled in and others just outlined, waiting for the subclass to provide the specifics.
Here's an example using animals and making sounds again:
PHP
<?php
abstract class Animal {
public function eat() {
echo "Eating food";
}
abstract public function makeSound();
}
class Dog extends Animal {
public function makeSound() {
echo "Bark";
}
}
class Cat extends Animal {
public function makeSound() {
echo "Meow";
}
}
$dog = new Dog();
$dog->eat();
$dog->makeSound();
$cat = new Cat();
$cat->eat();
$cat->makeSound();
?>
Output
Eating food
Bark
Eating food
Meow
In this case, the Animal abstract class has a concrete method eat() that all animals do the same way, and an abstract method makeSound() that needs to be defined in each subclass. The Dog and Cat classes provide their own implementations of makeSound(), showing different behaviors while sharing the same structure.
Frequently Asked Questions
Can PHP do polymorphism like other languages?
Yes, PHP can do polymorphism just like other object-oriented languages. It uses interfaces & abstract classes to let different classes use the same method names but with different actions.
Why is polymorphism useful in PHP?
Polymorphism is useful because it makes your code more flexible & reusable. It lets you write functions that work with different types of objects, making it easier to add new kinds without changing existing code.
How do interfaces differ from abstract classes in PHP?
Interfaces in PHP are like promises. If a class uses an interface, it must use all the methods the interface has, but it doesn't provide the method's code. Abstract classes can have some methods with code & some without, and classes that extend an abstract class must write the code for the methods without it.
Conclusion
Polymorphism in PHP is a powerful concept that allows for more flexible and reusable code. By understanding and implementing polymorphism through interfaces and abstract classes, you can design your PHP applications to be more modular and maintainable. Remember, the key to mastering polymorphism is practice, so try out these concepts in your projects to see how they can improve your code's structure and efficiency. With polymorphism, your PHP code can elegantly handle multiple data types and behaviors, making your applications more robust and versatile.
You can refer to our guided paths on the Coding Ninjas. You can check our course to learn more about DSA, DBMS, Competitive Programming, Python, Java, JavaScript, etc.
Also, check out some of the Guided Paths on topics such as Data Structure and Algorithms, Competitive Programming, Operating Systems, Computer Networks, DBMS, System Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry Experts.