Explain Polymorphism in PHP.


To begin with, Polymorphism is gotten from the Greek words Poly (which means many) and morphism (which meaning forms).

Polymorphism portrays an example in object-oriented programming where methods in various classes that do similar things should have a similar name. Polymorphism is essentially an OOP pattern that enables numerous classes with different functionalities to execute or share a commonInterface. The usefulness of polymorphism is code written in different classes doesn't have any effect which class it belongs because they are used in the same way. In order to ensure that the classes do implement the polymorphism guideline, we can pick between one of the two alternatives of either abstract classes or interfaces.

So let's implement the polymorphism principle with the help of the interface.

Interface An interface is similar to a class except that it cannot contain code. An interface can define method names and arguments, but not the contents of the methods. Any classes executing an interface must execute all methods characterized by the interface.

Example:

<?php
   interface Machine {
      public function calcTask();
   }
   class Circle implements Machine {
      private $radius;
      public function __construct($radius){
         $this -> radius = $radius;
      }
      public function calcTask(){
         return $this -> radius * $this -> radius * pi();
      }
   }
   class Rectangle implements Machine {
      private $width;
      private $height;
      public function __construct($width, $height){
         $this -> width = $width;
         $this -> height = $height;
      }
      public function calcTask(){
         return $this -> width * $this -> height;
      }
   }
   $mycirc = new Circle(3);
   $myrect = new Rectangle(3,4);
   echo $mycirc->calcTask();
   echo $myrect->calcTask();
?>

Output:

28.274
12

Explanation:

The interface with the name of " Machine" commits all the classes that implement it to define an abstract method with the name of calcTask(). In accordance, the Circle class implements the interface by defining the callTask() method with the respective body inside it. The rectangle class also implements the Machine interface but defines the method calcTask() with a different body that differs from the circle class CalTask() method. The polymorphism guideline says that, for this situation, all the methods that calculate the task would have the equivalent name. Now, at whatever point we would need to compute the Task for the different Classes, we would call a method with the name of calcTask() without giving a lot of consideration to the details of how to actually calculate the Task for the different Machine. The main thing that we would need to know is the name of the method that calculates the Task.

Updated on: 30-Jul-2019

9K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements