Back to results for “Dependency Injection”
PHP › Interfaces & Abstract Classes

What is an interface in PHP, and what purpose does it serve in defining a contract for classes to follow?

Beginner

Answer

An interface defines a set of method signatures that any class implementing that interface must provide, without specifying any actual implementation details itself, acting as a contract that guarantees any class implementing the interface will have those specific methods available, which lets different parts of your code depend on the interface rather than any particular concrete class, improving flexibility and testability.
interface Shape {
    public function area(): float;
}
class Circle implements Shape {
    public function __construct(private float $radius) {}
    public function area(): float { return M_PI * $this->radius ** 2; }
}
Real-world example A billing system defines a PaymentGateway interface with a charge method, and different concrete classes implement that same interface for different actual payment providers, letting the checkout code work with any provider interchangeably.

Common follow-ups: Can a class implement multiple interfaces at the same time?;What happens if a class does not implement every method required by an interface it claims to implement?