TExcelTAD
Home › PHP › PHP Interfaces

PHP Interfaces

An interface is a contract. It lists the public methods a class promises to provide, but it contains no implementation of its own. Any class that implements the interface must define every one of those methods, or PHP refuses to load the class.

Interfaces let you write code that depends on what an object can do instead of which class it is. A function that accepts a Shape does not care whether it receives a circle, a square or a class written next year — only that it has an area() method.

Declaring and implementing an interface

php · try it yourself
<?php
interface Shape
{
    public function area(): float;
    public function name(): string;
}

class Circle implements Shape
{
    public function __construct(private float $radius) {}

    public function area(): float
    {
        return round(M_PI * $this->radius ** 2, 2);
    }

    public function name(): string
    {
        return "circle";
    }
}

class Rectangle implements Shape
{
    public function __construct(private float $w, private float $h) {}

    public function area(): float
    {
        return $this->w * $this->h;
    }

    public function name(): string
    {
        return "rectangle";
    }
}

function describe(Shape $s): void
{
    echo "A {$s->name()} with area {$s->area()}\n";
}

describe(new Circle(2));
describe(new Rectangle(3, 4.5));
A circle with area 12.57
A rectangle with area 13.5

The describe() function type-hints the interface, so it works with any shape.

Rules for interfaces

Rule Detail
Methods Only signatures, no bodies; all must be public
Properties Not allowed (PHP 8.4 adds property hooks in interfaces, an advanced feature)
Constants Allowed: const VERSION = 2;
Multiple A class can implement many interfaces: implements A, B, C
Inheritance An interface can extend one or more other interfaces
Objects You cannot write new Shape() — interfaces cannot be instantiated

Implementing several interfaces

A class can only extend one parent class, but it can implement as many interfaces as it needs. This is how PHP lets one object play several roles.

php · try it yourself
<?php
interface Printable
{
    public function toText(): string;
}

interface HasPrice
{
    const CURRENCY = "EUR";
    public function price(): float;
}

class Ticket implements Printable, HasPrice
{
    public function __construct(private string $event, private float $cost) {}

    public function toText(): string
    {
        return "Ticket for {$this->event}";
    }

    public function price(): float
    {
        return $this->cost;
    }
}

$t = new Ticket("Jazz Night", 18.5);
echo $t->toText(), "\n";
echo $t->price(), " ", HasPrice::CURRENCY, "\n";

var_dump($t instanceof Printable);
var_dump($t instanceof HasPrice);
Ticket for Jazz Night
18.5 EUR
bool(true)
bool(true)

Tip: instanceof works with interfaces too. It is the safe way to check "can this object do X?" before calling a method.

Interfaces extending interfaces

Interfaces can build on each other with extends. A class implementing the child interface must provide the methods of the whole chain.

php · try it yourself
<?php
interface Readable
{
    public function read(): string;
}

interface Writable
{
    public function write(string $data): void;
}

interface Stream extends Readable, Writable
{
    public function size(): int;
}

class MemoryStream implements Stream
{
    private string $buffer = "";

    public function read(): string { return $this->buffer; }
    public function write(string $data): void { $this->buffer .= $data; }
    public function size(): int { return strlen($this->buffer); }
}

$m = new MemoryStream();
$m->write("Hello, ");
$m->write("interfaces!");
echo $m->read(), " (", $m->size(), " bytes)\n";

$names = class_implements($m);
sort($names);
echo implode(", ", $names), "\n";
Hello, interfaces! (18 bytes)
Readable, Stream, Writable

class_implements() returns every interface a class implements, including inherited ones. We sort the list because PHP does not promise a particular order.

Built-in interfaces you will meet

PHP itself ships with many interfaces. Implementing them lets your objects plug into language features:

Interface What it enables
Countable count($obj)
Stringable Automatically implemented by classes with __toString()
JsonSerializable Controls what json_encode($obj) produces
IteratorAggregate / Iterator foreach over the object
ArrayAccess $obj['key'] syntax
php · try it yourself
<?php
class Playlist implements Countable, JsonSerializable
{
    private array $songs = [];

    public function add(string $song): static
    {
        $this->songs[] = $song;
        return $this;
    }

    public function count(): int
    {
        return count($this->songs);
    }

    public function jsonSerialize(): mixed
    {
        return ["songs" => $this->songs, "total" => $this->count()];
    }
}

$p = (new Playlist())->add("Intro")->add("Theme")->add("Outro");
echo count($p), " songs\n";
echo json_encode($p), "\n";
3 songs
{"songs":["Intro","Theme","Outro"],"total":3}

Interface or abstract class?

Use an interface when unrelated classes should share a capability ("can be printed", "can be counted"). Use an abstract class when closely related classes should share real code and state. Many designs use both: an interface for the contract and an abstract class that implements part of it.

Note: If a class forgets a method, PHP reports a fatal error when the class is declared, such as "Class Foo contains 1 abstract method and must therefore be declared abstract or implement the remaining methods". You find the mistake immediately, not when the method is finally called.

Test yourself

How many interfaces can a single PHP class implement?

  1. Only one
  2. Up to two
  3. As many as needed
  4. None — only abstract classes can be implemented

Which of these is NOT allowed inside an interface?

  1. A constant
  2. A public method signature
  3. A method with a body
  4. Extending another interface

Which built-in interface lets count($obj) work on your object?

  1. Countable
  2. Iterator
  3. Stringable
  4. ArrayAccess