Understanding OOP Polymorphism in PHP with example
Polymorphism in PHP
- Polymorphism describes a pattern in object oriented programming in which classes have different functionality while sharing a common interface.
- The simple meaning of Polymorphism is ‘many forms’.
- Polymorphism allows us to use functions with same name but with different functionality.
class AnimalAs you can see, Bird isn’t all that different from Dog. They both eat food. However, because they are not the same type of Animal, they behave differently in response to the $food they are being fed. This is referred to as having their own implementations of the interface provided by Animal, or simply: implementations of Animal.
{
public $hungry = 'hell yeah.';
function eat($food)
{
$this->hungry = 'not so much.';
}
}
class Bird extends Animal
{
function eat($food)
{
if($food == 'seed')
{
$this->hungry = 'not so much.';
}
else
{
echo 'barf, I only like seed!';
}
}
}
This is at the core of the principle of polymorphism: Different types of objects can be handled in the same way, even though their implementations vary.
Advantage of Polymorphism:
- Code re-usability
- Maintainability – Extensibility
- Reduction in complexity
Source:- http://www.coderetina.com/
Comments
Post a Comment