Polymorphism
Last updated
What is Polymorphism?
Polymorphism is a core concept in object-oriented programming that PHP supports. It provides a mechanism to use one interface for different underlying forms, enabling different objects to process differently based on their data type. In PHP, polymorphism can be achieved through inheritance and interfaces. For example, you may have a parent class 'Shape' and child classes 'Circle', 'Rectangle', etc. They all can have a method 'draw' but with different implementations. It's not limited to classes; you can also use polymorphism with interfaces by implementing different classes with the same interface where each class will have different code for the same method.
Here's a small sample code demonstrating the concept:
<?php
interface Shape {
public function draw();
}
class Circle implements Shape {
public function draw() {
echo "Draw a circle";
}
}
class Rectangle implements Shape {
public function draw() {
echo "Draw a rectangle";
}
}
function drawShape(Shape $shape) {
$shape->draw();
}
drawShape(new Circle());
drawShape(new Rectangle());
?>
This creates a scalable way to add more shapes, as you only need to follow the 'Shape' interface.
Free resources to learn Polymorphism
- Open sourcePolymorphism
More in stage 12: PHP-FIG
Polymorphism: common questions
Can I learn Polymorphism in Hindi?
This lesson is written in English. Once you sign in, open it in the interactive course and ask the AI tutor to explain Polymorphism in Hindi or Hinglish. The tutor answers from this lesson’s own text, so it stays on the syllabus, and it runs on your own Google, OpenAI or Anthropic key.
Is this Polymorphism tutorial for beginners?
It is lesson 83 of 120 in the free PHP roadmap, in stage 12, PHP-FIG. If you are new to PHP, start from stage 1 and come back here in order; if you already know the earlier stages, this lesson stands on its own.