OOP polymorphism in PHP

Polymorphism is the consequence of the inheritance idea. In other words, class polymorphism is the property of a base class to use the functions of derivative classes, even if at the determination time it’s not clear which class will include it as a base one, and thus becoming its derivative class.

Let’s take a look at the polymorphism feature of classes on the following example:

<?php
class A {
// Displays the function of a class which has been called out
function Test() { echo "Test from A\n"; }
// Test function — just redirects to Test()
function Call() { Test(); }
}
class B extends A {
// Test function () for B class
function Test() { echo "Test from B\n"; }
}
$a=new A();
$b=new B();
?>

We use the following commands:

$a->Call(); // displays "Test from A"
$b->Test(); // displays "Test from B"
$b->Call(); // Attention! Displays "Test from B"!

You need to pay attention to the last line: it displays not the test function of A class, but of B class. Such a function which gets redefined in the derivative class is called virtual function.

The use of virtual functions allows users to replace the object of one class with the object of another class. Another classic example is a class which implements properties of a geometric figure, and some derivative classes – a circle, a square, a triangle, etc. Base class has the virtual function Draw(), which makes the object to draw itself. All other derivative classes redefine this function (because every figure is drawn in different way). Also, we have a figure array and we don’t know which figures are in it. By using polymorphism we can go over all of them and call the Draw function for each of them – the figure will decide its type on its own and how to draw it.

Here’s another example which illustrates polymorphism function:

<?php
class Base {
 function funct() {
 echo "<h2>Base class function</h2>";
 }
 function base_funct() {
 $this->funct();
 }
}

class Derivative extends Base {
 function funct() {
 echo "<h3>Derivative class function</h3>";
 }
}

$= new Base();
$= new Derivative();

$b->base_funct();
$d->funct();
$d->base_funct();
// Script displays:

// Base class function
// Derivative class function
// Derivative class function
?>

In this example, base_funct() function of a Base class has been re-recorded by the Derivative class function of the same name.