Swiftorial Logo
Home
Swift Lessons
AI Tools
Learn More
Career
Resources

Polymorphism in PHP

Introduction

Polymorphism is a core concept in object-oriented programming (OOP) that allows objects of different classes to be treated as objects of a common super class. It is a way to perform a single action in different forms. In PHP, polymorphism is mainly achieved through interfaces and inheritance.

Types of Polymorphism

There are two main types of polymorphism:

  • Compile-time Polymorphism: Also known as method overloading. PHP does not support method overloading directly.
  • Run-time Polymorphism: Achieved using inheritance and interfaces, where the method to be executed is determined at runtime.

Polymorphism with Inheritance

Polymorphism can be achieved through inheritance where a parent class reference is used to refer to a child class object.

<?php
class Animal {
    public function makeSound() {
        echo "Some generic animal sound";
    }
}

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

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

$animals = [new Dog(), new Cat(), new Animal()];

foreach ($animals as $animal) {
    $animal->makeSound();
    echo "<br>";
}
?>
                
Output:
Bark
Meow
Some generic animal sound

Polymorphism with Interfaces

Interfaces provide a way to achieve polymorphism in PHP. Different classes can implement the same interface, and objects of these classes can be treated uniformly.

<?php
interface Shape {
    public function draw();
}

class Circle implements Shape {
    public function draw() {
        echo "Drawing Circle";
    }
}

class Square implements Shape {
    public function draw() {
        echo "Drawing Square";
    }
}

$shapes = [new Circle(), new Square()];

foreach ($shapes as $shape) {
    $shape->draw();
    echo "<br>";
}
?>
                
Output:
Drawing Circle
Drawing Square

Conclusion

Polymorphism is a powerful feature in PHP that allows for flexible and maintainable code. By using inheritance and interfaces, you can write code that works on the interface level rather than the implementation level, promoting code reusability and scalability.