PHP 8.1 Enums Explained with Real Examples

Before PHP 8.1, “enums” meant a class full of class constants and hoping nobody passed an invalid value. Real enums finally gave PHP type-safe, self-documenting sets of fixed values.

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

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

function updateStatus(OrderStatus $status): void {
    echo $status->label();
}

updateStatus(OrderStatus::Shipped); // type-checked at the function boundary
echo OrderStatus::from('pending')->label(); // parse from a stored string value

Backed enums (the : string part) can round-trip to and from a database column cleanly via ->value and ::from(), making them a natural fit for status fields that used to be stored as loosely-typed strings.