Polymorphism in PHP with Example

Polymorphism in PHP is one of the important concept 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 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 is happened only in child class.

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

Polymorphism example in PHP

Here are are taking a simple example.

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

created another class childclass it inherits the feature of parentclass.

child class has also the same method name().

Defining the same method in child is know 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 example of Shapes.

Shape is a base class with a method show().

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

all have a over ridden 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

PHP Inheritance