In this tutorial, you will learn about polymorphism in OOP. And you’ll also learn what is the role of polymorphism in OOP, and why overriding and overloading are not supported in PHP & to overcome this interfaces and abstract classes play an important role to achieve polymorphism.
Polymorphism in Oops – PHP
What is polymorphism?
Polymorphism came from the Greek words Poly (which means many) and morphism (which means forms). like a single function having many signatures.
How to Implement Polymorphism in PHP?
Polymorphism in PHP can be implemented by either the use of interfaces or abstract classes. But incase other languages like C++, Java, and, .Net, etc the function overloading and function overriding are useful for implementing polymorphism. In PHP, function overloading and function overriding do not support it.
See some examples given below to get a clear idea about polymorphism in PHP
Here OnlineCalculator is an interface, which does not contain any kind of code, only a function. So using the interface we can use the same method to find the area of a circle and rectangle. Using implements
keyword we can implement an interface with a Class.
See the below example.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | <?php interface OnlineCalculator { public function getArea(); } // Get the Area of a Circle class Circle implements OnlineCalculator { private $radius; public function __construct($radius){ $this -> radius = $radius; } public function getArea(){ return $this -> radius * $this -> radius * pi(); } } // get the Area of a Rectangle class Rectangle implements OnlineCalculator { private $width; private $height; public function __construct($width, $height){ $this -> width = $width; $this -> height = $height; } public function getArea(){ return $this -> width * $this -> height; } } $mycircle = new Circle(3); $myrectangle = new Rectangle(3,4); echo $mycircle->getArea(); echo $myrectangle->getArea(); ?> |
Questions asked in the Interview on Polymorphism in PHP
- What is Polymorphism
- What is an Interface
- How to implement an interface in a Class