Object Oriented

Polymorphism

PHP

 

Polymorphism

PHP 5
interface InfoInterface {
  public function getInfo();
}

class Teacher implements InfoInterface {
  public $name;
  public $salary;
  
  public function __construct($name, $salary) {
    $this->name = $name;
    $this->salary = $salary;
  }
  
  public function getInfo() {
    return "name: " . $this->name .
         ", salary: " . $this->salary;
  }
}

class Student implements InfoInterface {
  public $name;
  public $gpa;
  
  public function __construct($name, $gpa) {
    $this->name = $name;
    $this->gpa = $gpa;
  }
  
  public function getInfo() {
    return "name: " . $this->name .
         ", gpa: " . $this->gpa; 
  }
}

Polymorphism provides a way for classes with different functionality to share a common interface.

Polymorphism lets you to have different objects from different classes, but with all of them guaranty to have at least a method with a same signature that can be called without knowing the type of the object.

$people = [
  new Student('Bob', 3.5),
  new Teacher('Alice', 80000),
  new Student('Emma', 4),
  new Student('Liam', 2.8)
];

for ($i=0; $i<count($people); $i++) {
  $person = $people[$i];
  print($person->getInfo());
}

The result for the code above will be:

name: Bob, gpa: 3.5
name: Alice, salary: 80000
name: Emma, gpa: 4
name: Liam, gpa: 2.8