Polymorphism is a key concept in object-oriented programming that allows different objects to respond differently to the same method call. In PHP, polymorphism is mainly achieved through inheritance and interfaces. This article explains the essence of PHP polymorphism with code examples.
Inheritance in PHP is used to reuse code and extend functionality. A subclass inherits the properties and methods of its parent class and can override parent methods to achieve polymorphism.
// Define an Animal class class Animal { public function speak() { echo "Animal makes a sound"; } } // Define a Dog class that extends Animal class Dog extends Animal { public function speak() { echo "Dog barks"; } } // Define a Cat class that extends Animal class Cat extends Animal { public function speak() { echo "Cat meows"; } } // Create a Dog object $dog = new Dog(); $dog->speak(); // Create a Cat object $cat = new Cat(); $cat->speak();
In this code, Animal is the parent class, and Dog and Cat are subclasses that override the speak method. Calling the same method on different objects produces different outputs, demonstrating polymorphism.
Interfaces define a set of methods without providing an implementation. Classes that implement an interface must implement the methods defined in the interface. This is another way PHP achieves polymorphism.
// Define an interface for objects that can make sounds interface Soundable { public function makeSound(); } // Dog class implements the interface class Dog implements Soundable { public function makeSound() { echo "Dog barks"; } } // Cat class implements the interface class Cat implements Soundable { public function makeSound() { echo "Cat meows"; } } // Create a Dog object $dog = new Dog(); $dog->makeSound(); // Create a Cat object $cat = new Cat(); $cat->makeSound();
Here, the Soundable interface defines the makeSound method. Dog and Cat implement the interface with their own specific behavior. Calling the same method on different objects produces different results, illustrating polymorphism.
Polymorphism through inheritance and interfaces allows developers to call the same method on different objects while achieving different behaviors. This increases code flexibility, maintainability, and scalability. Understanding the principles of polymorphism is fundamental for PHP object-oriented development.