PHP Polymorphism - Polymorphism in PHP



PHP Polymorphism

  • Polymorphism in PHP is the use of a single interface or class to refer to multiple different objects or classes.
  • It allows for code flexibility as the same code can be used for multiple objects and classes, saving time and effort when writing code.
  • Polymorphism allows for more abstract and flexible coding, which can lead to better code organization and shorter development cycles.
php-polymorphism

Sample Code

<?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 $lenght;
      private $height;
      public function __construct($lenght, $height){
         $this -> lenght = $lenght;
         $this -> height = $height;
      }
      public function calcTask(){
         return $this -> lenght * $this -> height;
      }
   }
   $mycirc = new Circle(5);
   $myrect = new Rectangle(5,4);
   echo $mycirc->calcTask();
   echo "<br>";
   echo $myrect->calcTask();
?>

Output

78.539816339745
20

Related Searches to PHP Polymorphism - Polymorphism in PHP