PHP Interfaces


In PHP, an interface is a way to define a contract or blueprint that classes must follow. Unlike abstract classes, interfaces cannot contain properties or method implementations; they only declare method signatures. Any class that implements an interface must define all the methods declared in the interface.

Interfaces are widely used to enforce consistent behavior across unrelated classes, promote polymorphism, and create flexible, maintainable code.

What is an Interface?

An interface defines what methods a class must have without specifying how these methods work. This allows different classes to implement the same interface differently while maintaining a consistent external API.

Key points about interfaces in PHP:

  • Interfaces cannot contain properties.

  • All methods in an interface are public by default.

  • A class can implement multiple interfaces, providing PHP’s way of achieving multiple inheritance.

  • Interfaces promote polymorphism and code decoupling.

Declaring an Interface

To declare an interface, use the interface keyword. Methods are declared without a body.

interface VehicleInterface {
    public function start();
    public function stop();
}

Here, VehicleInterface declares two methods: start() and stop(). Any class implementing this interface must provide definitions for both methods.

Implementing an Interface

A class implements an interface using the implements keyword:

class Car implements VehicleInterface {
    public function start() {
        echo "Car started.<br>";
    }

    public function stop() {
        echo "Car stopped.<br>";
    }
}

$car = new Car();
$car->start(); // Outputs: Car started.
$car->stop();  // Outputs: Car stopped.

The Car class fulfills the contract defined by the interface. If any method is missing, PHP throws a fatal error.

Multiple Interfaces

A single class can implement more than one interface, which allows combining different behaviors without using inheritance:

interface VehicleInterface {
    public function start();
}

interface HornInterface {
    public function honk();
}

class Bike implements VehicleInterface, HornInterface {
    public function start() {
        echo "Bike started.<br>";
    }

    public function honk() {
        echo "Bike honks.<br>";
    }
}

$bike = new Bike();
$bike->start(); // Outputs: Bike started.
$bike->honk();  // Outputs: Bike honks.

Multiple interfaces allow classes to adopt multiple behaviors, which is not possible with PHP’s single inheritance rule.

Interfaces vs Abstract Classes

Feature Interface Abstract Class
Properties Cannot have Can have
Method Implementation Cannot have Can have
Inheritance Multiple interfaces possible Single inheritance only
Use Case Define a contract Provide shared behavior and properties

Interfaces are ideal when you want unrelated classes to adhere to the same contract, while abstract classes are better when classes share common behavior or state.

Using Interfaces with Type Hinting

Interfaces can be used to enforce type hinting, ensuring that a function or method works with objects implementing a specific interface:

function startVehicle(VehicleInterface $vehicle) {
    $vehicle->start();
}

$car = new Car();
$bike = new Bike();

startVehicle($car);  // Works
startVehicle($bike); // Works

This allows for polymorphic behavior, where multiple types of objects can be passed into the same function.

Extending Interfaces

Interfaces can extend other interfaces, inheriting their method declarations:

interface ElectricVehicleInterface extends VehicleInterface {
    public function charge();
}

class ElectricCar implements ElectricVehicleInterface {
    public function start() {
        echo "Electric car started.<br>";
    }

    public function stop() {
        echo "Electric car stopped.<br>";
    }

    public function charge() {
        echo "Charging electric car.<br>";
    }
}

$eCar = new ElectricCar();
$eCar->start();  // Outputs: Electric car started.
$eCar->charge(); // Outputs: Charging electric car.

Extending interfaces allows you to build hierarchical contracts without implementing any functionality.

Best Practices

  1. Use interfaces when multiple classes share a common behavior but do not share state.

  2. Prefer interfaces over abstract classes when you want flexibility and multiple inheritance.

  3. Keep interface methods focused and minimal; avoid overloading with too many responsibilities.

  4. Combine interfaces with type hinting for robust, flexible code design.

  5. Name interfaces clearly, usually ending with Interface (e.g., LoggerInterface).

Common Mistakes

  • Forgetting to implement all methods declared in an interface.

  • Trying to include properties or method implementations inside an interface.

  • Using an interface when an abstract class is more appropriate for shared behavior.

  • Overloading an interface with unrelated methods, making it hard to maintain.

Summary of the Tutorial

  • Interfaces define a contract for classes without providing implementations.

  • Methods in interfaces are always public and must be implemented by any class using the interface.

  • Classes can implement multiple interfaces, achieving flexible behavior composition.

  • Interfaces are ideal for polymorphism, decoupling, and multiple inheritance scenarios.

  • Combining interfaces with type hinting and hierarchical design ensures clean, maintainable, and scalable code.

Mastering interfaces allows developers to design flexible applications, enforce consistent behavior across different classes, and achieve robust object-oriented PHP designs.


Practice Questions

  1. Create an interface VehicleInterface with methods start() and stop(). Create a class Car that implements this interface and provides definitions for both methods.

  2. Write an interface LoggerInterface with a method log($message). Create two classes FileLogger and DatabaseLogger that implement this interface differently.

  3. Create two interfaces VehicleInterface and HornInterface. Define methods start() in VehicleInterface and honk() in HornInterface. Create a class Bike that implements both interfaces.

  4. Write an interface ShapeInterface with a method area(). Create classes Rectangle and Circle that implement this interface and calculate their respective areas.

  5. Create an interface PaymentInterface with a method processPayment($amount). Create two classes CreditCardPayment and PayPalPayment that implement this interface and display a message showing payment processed.

  6. Write an interface ElectricVehicleInterface extending VehicleInterface and adding a method charge(). Create a class ElectricCar implementing this interface and define all methods.

  7. Create an interface DisplayInterface with a method display(). Write a function that accepts an object implementing DisplayInterface and calls the display() method. Demonstrate with a Product class.

  8. Write an interface EmployeeInterface with a method calculateSalary(). Create classes Manager and Developer implementing the interface with different salary calculations.

  9. Create an interface NotifierInterface with a method notify($message). Create classes EmailNotifier and SMSNotifier implementing the interface. Demonstrate polymorphism by storing both objects in an array and calling notify().

  10. Write an interface ReportInterface with methods generate() and export(). Create a class SalesReport implementing the interface, providing custom logic for both methods.


Try a Short Quiz.

coding learning websites codepractice

No quizzes available.

Go Back Top