PHP Polymorphism

Polymorphism in PHP, is an object oriented concept where same function can be used for different purposes.

Basically polymorphism means one name with many forms.

PHP Polymorphism Example

Here is a simple example on polymorphism in PHP.

<!DOCTYPE html>
<html>
<head>
   <title>Polymorphism Example in PHP</title>
</head>
<body>
<?php
   // this is example code of polymorphism in PHP - CodesCracker
   interface TutorialILike
   {
      public function likemsg();
   }
   class LikePHP implements TutorialILike
   {
      private $topic;
      public function __construct($topic)
      {
         $this->topic = $topic;
      }
      public function likemsg()
      {
         echo "I just love to read ".$this->topic." on CodesCracker<br/>";
      }
   }
   class LikeJava implements TutorialILike
   {
      private $topic;
      public function __construct($topic)
      {
         $this->topic = $topic;
      }
      public function likemsg()
      {
         echo "I just love to read ".$this->topic." on CodesCracker<br/>";
      }
   }
   class LikeC implements TutorialILike
   {
      private $topic;
      public function __construct($topic)
      {
         $this->topic = $topic;
      }
      public function likemsg()
      {
         echo "I just love to read ".$this->topic." on CodesCracker<br/>";
      }
   }
   class LikeHTML implements TutorialILike
   {
      private $topic;
      public function __construct($topic)
      {
         $this->topic = $topic;
      }
      public function likemsg()
      {
         echo "I just love to read ".$this->topic." on CodesCracker<br/>";
      }
   }
   $objPHP = new LikePHP("PHP");
   $objJava = new LikeJava("Java");
   $objC = new LikeC("C");
   $objHTML = new LikeHTML("HTML");
   echo $objPHP->likemsg();
   echo $objJava->likemsg();
   echo $objC->likemsg();
   echo $objHTML->likemsg();
?>
</body>
</html>

Here is the sample output produced by above PHP polymorphism example code:

php polymorphism

PHP Online Test


« Previous Tutorial Next Tutorial »