Friday 5 April 2019

Polymorphism in PHP

Polymorphism

 This means many forms.

According to the Polymorphism, methods in different classes that do similar things should have the same name.

Example: write a classes that represent geometric shapes (such as rectangles, circles and octagons) that are different from each other in the number of sides and in the formula that calculates their area, but they all have in common an area that can be calculated by a method.

The polymorphism principle says that, in this case, all the methods that calculate the area (and it doesn't matter for which shape or class) would have the same name.

Example, Call method that calculates the area calcArea() and put in each class that represents a shape.
Now, whenever we would want to calculate the area for the different shapes, we would call a method with the name of calcArea() without having to know about the area calculation logic for different shape.
The only thing that we would need to know is the name of the method that calculates the area.

Implement the polymorphism principle?
To implement the polymorphism, choose between abstract classes and interfaces.

Choose either abstract classes or interfaces to implement polymorphism.
Example: Create an interface named shape with calcArea() method in it.

interface Shape {
  public function calcArea();
}

Circle class implements the interface Shape by putting the formula of area calculation of circle in method calcArea().

class Circle implements Shape {
  private $radius;
   
  public function __construct($radius) {
    $this -> radius = $radius;
  }
  
  // calcArea calculates the area of circles 
  public function calcArea() {
    return $this -> radius * $this -> radius * pi();
  }
}

The rectangle class also implements the interface Shape but defines the method calcArea() with formula of area calculation for rectangles:

class Rectangle implements Shape {
  private $width;
  private $height;
   
  public function __construct($width, $height) {
    $this -> width = $width;
    $this -> height = $height;
  }
  
  // calcArea calculates the area of rectangles   
  public function calcArea() {
    return $this -> width * $this -> height;
  }
}
Now, create objects from the concrete classes:

$circ = new Circle(3);
$rect = new Rectangle(3,4);

All the above objects calculate area with the calcArea(), whether for rectangle object or circle object.

Use the calcArea() methods to calculate the area of the shapes:

echo $circ -> calcArea();
echo $rect -> calcArea();

Result:
28.274333882308
12

No comments:

Post a Comment