Polymorphism in PHP

Introduction

Polymorphism is one of the four core principles of Object-Oriented Programming (OOP):

  • Encapsulation
  • Inheritance
  • Abstraction
  • Polymorphism

The word Polymorphism means “many forms.”

In PHP, polymorphism allows different classes to use the same method name but perform different actions.

This makes your code flexible, scalable, and easier to maintain.

📌 What is Polymorphism?

Polymorphism allows objects of different classes to respond to the same method name in different ways.

In simple words:

👉 Same method name
👉 Different behavior

Polymorphism is usually achieved through:

  • Method Overriding
  • Interfaces (advanced topic)

In this tutorial, we will focus on method overriding.

Instead of writing complex if-else or switch statements, polymorphism lets objects decide their own behavior.

Why Do We Need Polymorphism?

Imagine you are building a system with different types of users:

  • Admin
  • Editor
  • Subscriber

Each user has a method called getRole().

Without polymorphism, you might write:

if ($userType == "admin") {
// do something
} elseif ($userType == "editor") {
// do something else
}

This becomes messy as your system grows.

Polymorphism removes this problem by letting each class define its own behavior.

Polymorphism Through Method Overriding

In PHP, polymorphism is commonly achieved using inheritance + method overriding.

Let’s understand with a clean example.

Basic Example: Animal Sound

<?php
class Animal {
public function sound() {
echo "Animal makes a sound.";
}
}class Dog extends Animal {
public function sound() {
echo "Dog barks.";
}
}class Cat extends Animal {
public function sound() {
echo "Cat meows.";
}
}
?>

Now use them:

<?php
$animals = [
new Dog(),
new Cat()
];foreach ($animals as $animal) {
$animal->sound();
echo "<br>";
}
?>

Output:

Dog barks.
Cat meows.

What Happened?

  • All classes have the same method name → sound()
  • Each class defines its own behavior
  • PHP decides at runtime which method to execute

This is called runtime polymorphism.

Polymorphism Using Type Hinting (Powerful Usage)

One of the most important real-world uses of polymorphism is when functions accept a parent class type.

<?php
function makeSound(Animal $animal) {
$animal->sound();
}makeSound(new Dog());
makeSound(new Cat());
?>

Why This Is Powerful

  • The function expects an Animal
  • It works with Dog and Cat
  • No conditions needed
  • Code becomes flexible and extendable

If tomorrow you add:

class Cow extends Animal {
public function sound() {
echo "Cow moos.";
}
}

You don’t change the function. It just works.

That is real scalability.

Real-World Example: Payment System

Let’s build a practical example.

<?php
abstract class Payment {
abstract public function pay($amount);
}class CardPayment extends Payment {
public function pay($amount) {
echo "Paid ₹$amount using Card.";
}
}class UpiPayment extends Payment {
public function pay($amount) {
echo "Paid ₹$amount using UPI.";
}
}
?>

Using polymorphism:

<?php
function processPayment(Payment $payment, $amount) {
$payment->pay($amount);
}processPayment(new CardPayment(), 500);
processPayment(new UpiPayment(), 700);
?>

Output:

Paid ₹500 using Card.
Paid ₹700 using UPI.

Same method → pay()
Different behavior → Card / UPI

This is real-world polymorphism.

Important Rules for Method Overriding

When overriding a method:

✔ Method name must be the same
✔ Parameters must match
✔ Visibility cannot be reduced

Example:

  • public → must remain public
  • protected → can stay protected or become public
  • public → ❌ cannot become private

Benefits of Polymorphism

Polymorphism helps you:

  • Write flexible code
  • Reduce if-else statements
  • Improve scalability
  • Follow clean architecture
  • Make applications easier to extend

It is heavily used in frameworks like Laravel and WordPress internally.

Common Beginner Mistakes

❌ Forgetting to use extends
❌ Misspelling method names
❌ Changing method visibility incorrectly
❌ Not understanding inheritance first

Make sure inheritance is clear before mastering polymorphism.

Best Practices

  • Use meaningful method names
  • Avoid unnecessary conditional logic
  • Design parent classes carefully
  • Use polymorphism to make systems extensible

Practical Task

Try this exercise:

  1. Create a parent class called Shape
  2. Add a method calculateArea()
  3. Create two child classes:
    • Circle
    • Rectangle
  4. Override calculateArea() in both classes
  5. Create a function that accepts Shape type and prints area
  6. Pass different objects to the function

Observe how the same method behaves differently.

Summary

  • Polymorphism means “many forms.”
  • It allows the same method to behave differently.
  • Achieved using inheritance and method overriding.
  • PHP decides which method to execute at runtime.
  • It makes your applications scalable and flexible.

Polymorphism, along with inheritance and encapsulation, forms the foundation of powerful OOP applications.

In the next tutorial, we’ll learn about Abstract Classes in PHP.

Related Tutorials

  • Introduction to Object-Oriented Programming (OOP) in PHP

    Introduction As PHP projects grow, managing code using simple procedural programming becomes difficult. Files become longer, functions are scattered, and maintaining the project becomes time-consuming. This is where Object-Oriented Programming (OOP) becomes useful. OOP helps you organize your PHP code in a structured way by grouping related data and functionality together. Instead of writing everything…

  • Classes & Objects in PHP

    Introduction In Object-Oriented Programming (OOP), classes and objects are the foundation of everything. Understanding these two concepts clearly will make the rest of OOP much easier to learn. In simple terms, a class is a blueprint, and an object is a real instance created from that blueprint. In this tutorial, you will learn what classes…

  • Constructors & Destructors in PHP

    Introduction In Object-Oriented Programming, constructors and destructors are special methods that automatically run at specific moments in an object’s lifecycle. A constructor runs when an object is created.A destructor runs when an object is destroyed. These methods help initialize and clean up resources in a PHP application. Understanding them is essential for writing structured and…

  • Access Modifiers in PHP (public, private, protected)

    Introduction In Object-Oriented Programming, access modifiers control the visibility of properties and methods inside a class. They determine: In PHP, there are three main access modifiers: Understanding access modifiers is important because they help protect data and improve code security and structure. Why Are Access Modifiers Important? Without access control, anyone could change the internal…

  • Inheritance in PHP

    Introduction Inheritance is one of the most important concepts in Object-Oriented Programming (OOP). It allows one class to inherit the properties and methods of another class. In simple words, inheritance helps you reuse existing code instead of rewriting it. This makes your code cleaner, more structured, and easier to maintain. In this tutorial, you will…

  • Encapsulation in PHP

    Introduction Encapsulation is one of the core principles of Object-Oriented Programming (OOP). It refers to the concept of restricting direct access to certain parts of an object and allowing controlled access through methods. In simple words, encapsulation means data hiding. Instead of allowing users to directly access and modify object properties, we protect them using…

Leave a Reply

Your email address will not be published. Required fields are marked *