The word Polymorphism comes from Greek and literally means "many forms" or the ability to take on multiple forms. In object-oriented programming, this means that different classes can implement the exact same method name, but each executes it in its own specific way. When we call this method, PHP automatically determines behind the scenes which object it belongs to and runs the correct code.
Imagine a universal remote control with a PLAY button. This button is a single method that you can press on different devices (objects):
The command or method call is always completely identical (play()), but the final result depends on
the device you are controlling. This is polymorphism in practice!
The main power of polymorphism lies in the fact that it allows us to write extremely flexible code. We can create a single main function that accepts a general type (e.g., an interface or a parent class), and then we can pass any subclass to it without changing the code.
If you were to add a new class to your application in the future (e.g., ElectricScooter), you would
not need to change the existing functions for driving. As long as the scooter follows the same rules and has a
method for moving, the system will work without a single modification!
Beginners often confuse these two terms because they are closely related. Take a look at their mutual relationship:
| OOP Concept | Main Goal | Approach in Code |
|---|---|---|
| Inheritance | Code reuse (DRY). | A child takes code from the parent so it does not have to be rewritten. |
| Polymorphism | Flexibility and a unified interface. | Different children have methods with the same name but completely different behavior. |