Search⌘ K
AI Features

Introduction and Implementation of Polymorphism

Explore the concept of polymorphism in PHP OOP to write methods with the same name across different classes. Understand how to use interfaces to enforce method implementation and handle multiple shapes with a single method call to calcArea(), improving code flexibility and readability.

What is polymorphism?

According to the polymorphism principle (“poly” is the Greek word for “many”), methods in different classes that do similar things should have the same name.

A prime example is that of classes that represent geometric shapes (such as rectangles, circles, and octagons) which are different from each other in the number of sides and in the formula that calculates their area but all have an area in common that needs to be calculated. In such a case, the polymorphism principle says that all the methods that calculate the area (it doesn’t matter for which shape or class) should have ...