Categories
PHP

OOP Polymorphism

Polymorphism is a design pattern in which classes have different functionality while sharing a common interface.

Polymorphism is a design pattern in which classes have different functionality while sharing a common interface. You can define an interface in PHP using interface or abstract classes.

The example given below will describe the general concept of polymorphism, and how it can easily be written in PHP. The interface with the name of Shape commits all the classes that implement it to define an abstract method with the name of area().

Step 1 : Declare interface using interface keyword and define area() method (methods must be defined in the interface without the body).

<?php
 interface Shape {
  public function area();
 }

Step 2: Create Circle class that implements the Shape interface. Write the formula that calculates the area of circles in the area() method and return the result:

<?php
 class Circle implements Shape {
  private $radius; 
  public function __construct($radius) {
   $this -> radius = $radius;
  }

  public function area() {
   $area = $this -> radius * $this -> radius * pi();
   return $area;
  }
 }

Step 3: Create a new class Rectangle, the Rectangle class also implements the Shape interface but defines the method area() with a calculation formula that is suitable for rectangles:

<?php
class Rectangle implements Shape {
 private $width; 
 private $height;

 public function __construct($width,$height) {
 $this -> width  = $width;
 $this -> height = $height;
 }

 public function area() {
 return $this -> width * $this -> height;
 }
}

By implementing a common interface we can be sure that all of the objects calculate the area with the method that has the name of area(), whether it is a rectangle object or a circle object (or any other shape).

$rect = new Rectangle(3,3);
echo $rect -> area();

$circ = new Circle (5);
echo $circ -> area();

PHP OOP Tutorials: