Open In App

How to implement Polymorphism in PHP?

Polymorphism is a core principle of object-oriented programming (OOP) where objects of different classes can be treated as objects of a common superclass. It allows methods to perform different actions based on the object they are called upon, enhancing code flexibility and reusability.

Syntax:

// Parent class
class Animal {
public function makeSound() {
return "Animal makes a sound.";
}
}

// Child class overriding makeSound() method
class Dog extends Animal {
public function makeSound() {
return "Dog barks.";
}
}

Here, Animal is a parent class with a method makeSound() returning a generic sound. Dog is a child class that extends Animal and overrides makeSound() to return “Dog barks.”.

Method Overriding:

Dynamic Binding:

Interfaces and Abstract Classes:

Example with Interface:

// Interface
interface Shape {
public function draw();
}

// Classes implementing the Shape interface
class Circle implements Shape {
public function draw() {
return "Drawing circle.";
}
}

class Square implements Shape {
public function draw() {
return "Drawing square.";
}
}

Explanation: Declares an interface Shape with a draw() method signature. Two classes, Circle and Square, implement the Shape interface by providing their own draw() method implementations. Each class defines how to draw its respective shape, adhering to the contract specified by the Shape interface.

Article Tags :