Polymorphism in php

In the last lesson we learnt about interface and how they are different to abstract classes. Today in this lesson we will learn about a very important topic which is Polymorphism

What is polymorphism in php ?

Lets break the word and find this : Polymorphism word is made of two words i.e (Poly + morphism). Poly means many and morphism means ability to take multiple form.

In simple words, we can say that polymorphism is the feature of Object oriented programming in which a method name can have same name but of different form. Lets take a real life example to understand this more clearly.

Situation 1.  A person say Ram,  can be a husband, a father, a lover, a brother. His name is Ram but he is playing different types of roles at different situations.

Situation 2. We need to find the area of something that can be, (circle, rectangle, square e.t.c ). We have to find area i.e ONE NAME, and area of circle, rectangle, square. Here circle, rectangle and square are the form.

Polymorphism says that if methods of different classes doing the similar things then their name should be same.

From the above situations you might have understood that what polymorphism means ? Let’s take an example to understand the implementation of polymorphism.

We can use class also in order to understand this. But i am using interface here because in the last lesson we have learnt interface so that you will get its revision also.

Now we have to find the area of the circle, rectangle. So we will be using three class with these name respectively.

Output : 

Area of Circle is 78.539816339745
Area of Rectangle is 15

In the above example we created an interface whose name is Math and two class Circle and Rectangle having method name  area which calculates the area of circle and rectangle. Observer from both the classes we are calling the same method name i.e area()

 

Leave a Reply

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