Using PHP Class Interface

 ← Dev Articles
👍 0
👎 1

In PHP, an interface defines a contract or blueprint that any class implementing it must follow.

It specifies method signatures (the names, parameters, and visibility of methods), however does  not implement the methods.

A class that implements an interface must define all of the methods declared in the interface.

Interfaces help achieve abstraction and multiple inheritance (since a class can implement multiple interfaces).


Example:


// Define an interface

 interface Employee {

    public function clockIn(string $message);

 }

 

 // Implement the interface in a class

 class Engineer implements Employee {

    public function clockIn(string $message) {

        echo "Engineer Clock In: " . PHP_EOL;

    }

 }

 

 // Another class implementing the same interface

 class Mechanic implements Employee {

    public function clockIn(string $message) {

        echo "Mechanic Clock In: " . PHP_EOL;

    }

 }

 

 // Usage

 function processTask(Employee $employee) {

    $employee->clockIn("Task has been processed!");

 }

 

 // You can swap implementations easily

 $engineer = new Engineer();

 $mechanic = new Mechanic();

 

 processTask($engineer);  // Clock In Engineer

 processTask($mechanic);    // Clock In Mechanic

 

 

What interfaces can contain:

 - Method declarations (no body/implementation)

 - Constants (e.g. const MAX_LIMIT = 100;)

What interfaces cannot contain:

 - Properties/variables

 - Constructors with implementation

 - Method bodies

Example:

 

 interface ExampleInterface {

    // Allowed

    public function doSomething();

 

    // Allowed

    const VERSION = "1.0";

 

    // Not allowed: properties inside interfaces

    // public $name;   // This will cause an error

 }