How does PHP's type system use interfaces to enable polymorphism, allowing different concrete classes to be used interchangeably wherever the interface type is expected?
Short answer
Polymorphism lets you write code that operates on an interface type without needing to know the specific concrete class it is actually working with at runtime, meaning a function accepting a parameter typed to a specific interface can accept any object from any class that…
Advertisement
AModel answer
Polymorphism lets you write code that operates on an interface type without needing to know the specific concrete class it is actually working with at runtime, meaning a function accepting a parameter typed to a specific interface can accept any object from any class that implements that interface, and PHP correctly calls whichever specific implementation belongs to the actual object passed in, allowing genuinely flexible, extensible code that can work with new implementations added later without any changes to the code using the interface.
function printArea(Shape $shape) {
echo $shape->area();
}
printArea(new Circle(5));
printArea(new Rectangle(4, 6));Real-world example
A reporting function accepts any object implementing the Shape interface, correctly calculating and printing the area whether it receives a Circle, a Rectangle, or an entirely new shape class added to the codebase much later.
Likely follow-ups
- What is the difference between polymorphism achieved through interfaces versus through class inheritance?
- How does PHP determine which specific method implementation to actually call at runtime?
Related topics