Polymorphism

Polymorphism means that you are deriving from a base class to create a new class, and the polymorphism is when you derive from the base class and implement a interface functions, so that any derived class will have to these functions implement so if you call a function that is defined by the interface to be present, you know it will be implement in some forum.

In php, there is a interface type, so we can define a basic Animal type to print is name, so that any animal that is derived from this interface will have to implement at least the print name function, here is the interface

interface Animal
{
  public function printName();
}

it is very similar to a class structure apart from there is no functional code, just the function definition. To then implement the interface Animal within a class, so that you will know that the printName() function will be implemented you use the “implements” keyword in the class definition as below.

class Cat implements Animal
{....

and then the class Cat will have to define the printName function as

  public function printName()
  {
     echo "Cat class\n";
  }

otherwise if you did not implement it there would be a error on the “compile time” as below.

Fatal error: Class Cat contains 1 abstract method and must therefore be declared abstract or implement the remaining methods (Animal::printName)

here is a full code that will do a Cat and Dog class, then you can create a array of different derived Animals interfaces and then just call the printName and you know it will be present.

<?php
interface Animal
{
  public function printName();
}
 
class Cat implements Animal
{
      public function printName()
      {
	echo "Cat class\n";
      }
};
 
class Dog implements Animal 
{
      public function printName()
      {
	echo "Dog class\n";
      }
};
 
$animals = Array(
    new Cat(), new Dog()
    );
 
foreach ($animals as $a)
{
    $a->printName();
}
 
?>

and the output would be

Cat class
Dog class

Polymorphism is great, because you just know that certain functions will be implemented.

Leave a Reply

Your email address will not be published. Required fields are marked *