PHP Interfaces
An interface defines a contract of method names that a class promises to implement, without providing any of the actual code.
What is an interface?
An interface is a list of method signatures with no bodies. It describes what a class must be able to do, but not how it does it. When a class agrees to an interface using the implements keyword, PHP requires that class to define every method the interface lists. This lets you rely on a shared set of capabilities across unrelated classes.
Defining and implementing an interface
<?php
interface Shape
{
public function area(): float;
}
class Circle implements Shape
{
public function __construct(private float $radius)
{
}
public function area(): float
{
return 3.14159 * $this->radius ** 2;
}
}
class Square implements Shape
{
public function __construct(private float $side)
{
}
public function area(): float
{
return $this->side ** 2;
}
}
$shapes = [new Circle(2), new Square(3)];
foreach ($shapes as $shape) {
echo $shape->area() . "\n"; // 12.56636 then 9
}
?>Because both Circle and Square implement Shape, code that expects a Shape can work with either one without caring which it received. This is a practical form of polymorphism: the loop above calls area() on each object and each class supplies its own calculation.
Interfaces versus abstract classes
An interface only describes method signatures and cannot contain working code or properties. An abstract class can provide some finished methods and shared state while still leaving other methods for subclasses to fill in. A class can implement many interfaces but can extend only one class, so interfaces are the flexible choice when you need a type to fit several roles.
Implementing multiple interfaces
A single class can implement several interfaces at once by separating their names with commas. This lets you compose a class from several small, focused contracts instead of one large one, keeping each interface easy to reason about.
One class, several interfaces
<?php
interface Drawable
{
public function draw(): string;
}
interface Resizable
{
public function resize(float $factor): void;
}
class Icon implements Drawable, Resizable
{
public function __construct(private float $size)
{
}
public function draw(): string
{
return "Icon at size " . $this->size;
}
public function resize(float $factor): void
{
$this->size *= $factor;
}
}
$icon = new Icon(16);
$icon->resize(2);
echo $icon->draw(); // Icon at size 32
?>- Declare an interface with the interface keyword and list method signatures only.
- A class joins an interface with implements and must define every listed method.
- Interface methods are always public.
- A class can implement multiple interfaces, separated by commas.
- Interfaces let you write code against a capability rather than a specific class.