Login |  Register 
I had no idea at all about PHP or programming until I started reading your website!
Scott
 

Introduction to PHP and Polymorphism

Polymorphism is a key skill in object orientated programming that allows developers to write better more flexible code.

It does this by eliminating the need for if and switch statements when determining behaviour.

This is done by relying on a interface or base class therefore when creating any logic as long as the code only uses a interface or base class methods there will be no need to use if statements as each class will implement the base class or interface methods in its own way.

interface IAnimal
{
 public function makeNoise();
}

class Cat implements IAnimal
{
 public function makeNoise()
 {
  return "Meow";
 }
}

class Dog implements IAnimal
{
 public function makeNoise()
 {
  return "Woof";
 }
}

Therefore with the above code a developer doesn't need to know about what type of class the animal is in order to make a sound as long as the object is of type IAnimal it will handle this itself.

Of course this can be repeated with classes by using a base class with the makeNoise method and then overriding this in the child classes.

Below is a example of not using Polymorphism.

class Cat
{
 public function Meow()
 {
  return "Meow";
 }
}

class Dog
{
 public function Woof()
 {
  return "Woof";
 }
}

//Code to determine the action
if ($animal instanceof Dog)
{
   echo $animal->Woof();
}
else
{
   echo $animal->Meow();
}

As you can see because there is no standardised method between the classes extra logic needs to be used to ensure the correct method is called.


No comments have been provided.
security image
Written by Dominic Skinner
Last Updated: 2011-10-25 16:00:38