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.
Here is an example code:
class 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!';
}
}
}
As 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.
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/
    For more about polymorphism  http://net.tutsplus.com/tutorials/php/understanding-and-applying-polymorphism-in-php/

     

    Comments

    Popular posts from this blog

    8 Best CMSs for building a well structured social networking website

    Manor House - Telscombe Village