0
0
PHPprogramming~5 mins

Why interfaces are needed in PHP

Choose your learning style9 modes available
Introduction

Interfaces help make sure different parts of a program can work together by agreeing on what methods they must have.

When you want different classes to share the same set of methods but have different behaviors.
When you want to write code that can work with many types of objects in the same way.
When you want to make your code easier to change or add new features without breaking existing parts.
Syntax
PHP
<?php
interface InterfaceName {
    public function method1();
    public function method2($param);
}

class ClassName implements InterfaceName {
    public function method1() {
        // code here
    }
    public function method2($param) {
        // code here
    }
}
?>

Interfaces only declare methods, they do not provide the method's code.

Classes that implement an interface must write the code for all its methods.

Examples
This example shows an interface Logger with one method. The class FileLogger implements it by writing the message.
PHP
<?php
interface Logger {
    public function log(string $message);
}

class FileLogger implements Logger {
    public function log(string $message) {
        echo "Logging to a file: $message";
    }
}
?>
Here, Shape interface requires an area method. The Circle class implements it with its own calculation.
PHP
<?php
interface Shape {
    public function area();
}

class Circle implements Shape {
    private float $radius;
    public function __construct(float $radius) {
        $this->radius = $radius;
    }
    public function area() {
        return pi() * $this->radius * $this->radius;
    }
}
?>
Sample Program

This program shows an interface Vehicle with a method startEngine. Two classes implement it differently. A function uses the interface type to start engines without caring about the exact vehicle type.

PHP
<?php
interface Vehicle {
    public function startEngine();
}

class Car implements Vehicle {
    public function startEngine() {
        echo "Car engine started.";
    }
}

class Motorcycle implements Vehicle {
    public function startEngine() {
        echo "Motorcycle engine started.";
    }
}

function startVehicleEngine(Vehicle $vehicle) {
    $vehicle->startEngine();
}

$car = new Car();
$motorcycle = new Motorcycle();

startVehicleEngine($car);
echo "\n";
startVehicleEngine($motorcycle);
?>
OutputSuccess
Important Notes

Interfaces help keep code organized and clear by defining what methods a class must have.

They allow different classes to be used interchangeably if they implement the same interface.

Summary

Interfaces define a set of methods without code.

Classes that implement interfaces must write all those methods.

This helps different classes work together and makes code easier to manage.