Object Oriented

Interface

PHP

 

Interface

PHP 5
interface myInterface {
  
  // ...
  
}

Interface is a tool to achieve better abstraction.

Interface specifies a list of methods that Classes should implement.

Interface is a blueprint for Classes, just like Class are blueprints for Objects.

 

Interface Method

PHP 5
interface JobInterface {
  public function work();
}

class Teacher implements JobInterface {
  public function work() {
    print("I'm teaching");
  }
}

In this, any Class that is not abstract and implements the JobInterface should implement the work method, otherwise PHP engine throws an error.

A Class can implement one or more Interfaces separated by a comma (,).

 

Interface Constant

PHP 5
interface JobInterface {
  const MINIMUM_WAGE = 7.25;
  
  public function work();
}

class Teacher implements JobInterface {
  public function work() {
    print("Teach for not less than " . $this::MINIMUM_WAGE);
  }
}

Interface may contain constants.

$teacher1 = new Teacher();
$teacher1->work();  // Teach for not less than 7.25

There are couple of ways to access Interface Constants (based on the context):

JobInterface::MINIMUM_WAGE
Teacher::MINIMUM_WAGE
$this::MINIMUM_WAGE
$teacher1::MINIMUM_WAGE
 

Abstract Class

PHP 5
abstract class Teacher {
  public $name;
  
  public function greet() {
    print("Hello Students!"); 
  }
  
  abstract function work();
}

class PhysicsTeacher extends Teacher {
  public function work() {
    print("I'm teaching physics!");
  }
}

Abstract Class is a specified abstract.

Abstract Class can have abstract methods.

Abstract Method is a method without an implementation.

Abstract Classes cannot be instantiated, because they are specified incomplete.

In PHP you can only extend from one parent Class.

$teacher1 = new PhysicsTeacher();
$teacher1->greet(); // Hello Students!
$teacher1->work();  // I'm teaching physics!