Polymorphism in PHP with Example

Polymorphism in PHP is one of the important concepts in OOPs.

Polymorphism is a Greek word. Polymorphism is created by two different words poly (means many) and morph (means forms).

It is another functionality of OOPS. In a programming language, two types of Polymorphism are there.

  1. Function overriding (Run time Polymorphism)
  2. Function Overloading(Compile time Polymorphism)

Function Overriding in PHP

Overriding happens only in child class.

If the parent class declares a function and the child class wants to override the parent class function then function overriding means run time polymorphism happened.

Polymorphism example in PHP

Here are taking a simple example.

Created a class parent class it has a method name().

created another class child class it inherits the feature of the parent class.

child class has also the same method name().

Defining the same method in a child is known as method overriding.

Output

 
Calling show method of Shape
Shape is no defined
Calling show method of Circle
Showing a Circle
Calling show method of Rectangle
Showing a Rectangle
Calling show method of Square
Showing a Square
Calling show method of Triangle
Showing a Triangle

Polymorphism example to call different methods in PHP

Here we have taken the example of Shapes.

The shape is a base class with a method shown ().

Child classes of Shape are Circle, Rectangle, Square, and Triangle.

all have an overridden method show().

Polymorphism Example in PHP

Output

 
Calling show method of Shape
Shape is no defined
Calling show method of Circle
Showing a Circle
Calling show method of Rectangle
Showing a Rectangle
Calling show method of Square
Showing a Square
Calling show method of Triangle
Showing a Triangle

Read More

  1. PHP Inheritance