devnotes.

Interfaces, Traits, and Enums

Interfaces define a contract — a set of method signatures a class promises to implement — with no shared implementation. A class can implement multiple interfaces:

interface Payable
{
    public function pay(float $amount): bool;
}

interface Refundable
{
    public function refund(float $amount): bool;
}

class CreditCardProcessor implements Payable, Refundable
{
    public function pay(float $amount): bool { /* ... */ return true; }
    public function refund(float $amount): bool { /* ... */ return true; }
}

Traits solve PHP's lack of multiple inheritance by letting you share actual method implementations across unrelated classes:

trait Loggable
{
    public function log(string $message): void
    {
        error_log(static::class . ": $message");
    }
}

class OrderService
{
    use Loggable;
}

Enums (PHP 8.1+) represent a fixed set of possible values, replacing the old pattern of class constants for this purpose:

enum OrderStatus: string
{
    case Pending   = 'pending';
    case Shipped   = 'shipped';
    case Delivered = 'delivered';

    public function label(): string
    {
        return match ($this) {
            self::Pending   => 'Awaiting shipment',
            self::Shipped   => 'On the way',
            self::Delivered => 'Delivered',
        };
    }
}

$status = OrderStatus::Shipped;
echo $status->value; // 'shipped'
echo $status->label(); // 'On the way'

Enums can implement interfaces and have their own methods, making them far more powerful than simple constants while guaranteeing type safety.

PHP Interfaces, Traits, and Enums Explained | DevNotes