iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

PHP Enums (8.1+)

PHP 8.1 added first-class enums — a fixed, named set of cases. Type-safe replacement for const PAID = 'paid'; string constants.

Pure enum (no backing value)

PHP
enum Suit {
    case Hearts;
    case Diamonds;
    case Clubs;
    case Spades;
}

$s = Suit::Hearts;
echo $s->name;   // 'Hearts'

Backed enum

Each case has a string or int value. The most common form — pairs with database columns.

PHP
enum Status: string {
    case Paid     = 'paid';
    case Pending  = 'pending';
    case Refunded = 'refunded';
}

echo Status::Paid->value;          // 'paid'
$s = Status::from('paid');           // throws if value isn't valid
$s = Status::tryFrom('huh');         // returns null instead of throwing

Methods on an enum

PHP
enum Status: string {
    case Paid     = 'paid';
    case Pending  = 'pending';
    case Refunded = 'refunded';

    public function label(): string {
        return match ($this) {
            self::Paid     => 'Paid',
            self::Pending  => 'Awaiting payment',
            self::Refunded => 'Refund issued',
        };
    }

    public function isOpen(): bool {
        return $this === self::Pending;
    }
}

echo Status::Pending->label();   // Awaiting payment

Listing the cases

PHP
foreach (Status::cases() as $c) {
    echo $c->name, ' => ', $c->value, PHP_EOL;
}

As a type hint

PHP
function process(Status $status): string {
    return $status->label();
}
Tip: Backed enums serialise neatly to JSON / DB. Pure enums are best when there's no natural value — direction, traffic-light colour, card suit.

Example

Example
<?php
// PHP 8.1+
enum Status: string {
    case Paid     = 'paid';
    case Pending  = 'pending';
    case Refunded = 'refunded';
}
echo Status::Paid->value;
Try it Yourself »

Exercise

Backed-enum declaration syntax.

Status: string { case Paid = 'paid'; }

Test yourself

Q1. Enums arrived in PHP…
Q2. A backed enum has…
Q3. Status::tryFrom("bad") returns…

Discussion

Loading…