In PHP, an interface is a way to define a contract that classes can implement. Interfaces allow you to specify methods that a class must implement without defining how those methods should be executed. This promotes a consistent structure across different classes and can be useful for defining common behaviors in a flexible and modular way.

Defining an Interface

To define an interface, use the interface keyword. An interface can include method declarations, but it cannot include any method implementations.

  <?php
interface Vehicle {
    // Method declarations
    public function start();
    public function stop();
}
?>
  

Implementing an Interface

To implement an interface in a class, use the implements keyword. The class must provide concrete implementations for all methods declared in the interface.

  <?php
class Car implements Vehicle {
    // Implementing the start method
    public function start() {
        echo "Car is starting.";
    }

    // Implementing the stop method
    public function stop() {
        echo "Car is stopping.";
    }
}
?>
  

Using an Interface

You can create instances of classes that implement the interface and call the methods defined by the interface.

  <?php
$myCar = new Car();
$myCar->start(); // Outputs: Car is starting.
$myCar->stop();  // Outputs: Car is stopping.
?>
  

Multiple Interfaces

A class can implement multiple interfaces by separating them with commas.

  <?php
interface Drivable {
    public function drive();
}

interface Refillable {
    public function refuel();
}

class Motorcycle implements Drivable, Refillable {
    public function drive() {
        echo "Motorcycle is driving.";
    }

    public function refuel() {
        echo "Motorcycle is refueling.";
    }
}
?>
  

Interface Inheritance

An interface can extend another interface. The extending interface inherits all methods from the parent interface.

  <?php
interface Engine {
    public function start();
    public function stop();
}

interface ElectricEngine extends Engine {
    public function charge();
}

class ElectricCar implements ElectricEngine {
    public function start() {
        echo "Electric car is starting.";
    }

    public function stop() {
        echo "Electric car is stopping.";
    }

    public function charge() {
        echo "Electric car is charging.";
    }
}
?>
  

Key Points

  • Interfaces Define a Contract: They specify what methods a class must implement but not how they should be implemented.
  • Methods in Interfaces Are Public: All methods in an interface are implicitly public.
  • No Property Declarations: Interfaces cannot have properties, only method declarations.

Interfaces are useful for ensuring that a class follows a specific contract and for achieving polymorphism in object-oriented programming.