Open In App

How to implement Polymorphism in PHP?

Last Updated : 19 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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:

  • We can implement polymorphism in PHP by overriding methods defined in the parent class within the child class.
  • Child classes provide their own implementation of the method with the same name and signature as the parent class method.

Dynamic Binding:

  • PHP uses dynamic binding to determine which method implementation to execute at runtime based on the object type.
  • When a method is called on an object, PHP resolves the method implementation based on the object’s actual class type.

Interfaces and Abstract Classes:

  • Interfaces and abstract classes can also facilitate polymorphism in PHP by defining a common set of method signatures that concrete classes must implement.
  • Objects of different classes implementing the same interface can be treated interchangeably.

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.


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads