AnyCompiler

Interfaces and Traits

PHP classes can only extend one parent, but a class can implement any number of interfaces, and use any number of traits — PHP's two distinct answers to wanting more than single inheritance gives you. An interface declares method signatures with no bodies at all — a pure contract, a promise that "any class implementing me has these methods" — and a class can implement as many interfaces as it needs, comma-separated. A trait is the opposite: it's real method bodies, written once and mixed into any class with use TraitName — PHP's way of sharing actual implementation across otherwise-unrelated classes without a shared base class.

<?php
interface Shape {
    public function area(): float;
}

trait Describable {
    public function describe(): string {
        return "This shape has area " . $this->area();
    }
}

class Circle implements Shape {
    use Describable;

    private float $radius;

    public function __construct(float $radius) {
        $this->radius = $radius;
    }

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

$c = new Circle(2);
echo round($c->area(), 2), "\n";
echo $c->describe(), "\n";
var_dump($c instanceof Shape);
Output
12.57
This shape has area 12.566370614359
bool(true)

Circle implements Shape, so PHP enforces that it really does define area() with a matching signature — $c instanceof Shape confirms that contract held. use Describable pulled in a fully working describe() method with no code written inside Circle at all; describe() calls $this->area(), and because $this is a Circle at runtime, that calls Circle's own area() — a trait's methods run in the context of whatever class mixes them in. Next: working with strings and arrays together — array_map() and array_filter() as PHP's answer to comprehensions, applied to real text processing.

Practice exercise

Write a Greeter interface with greet(): string, a Loud trait with a shout() method that returns strtoupper($this->greet()), and a Robot class implementing Greeter and using Loud, where greet() returns "beep boop" — then echo (new Robot())->shout().