TExcelTAD
Home › PHP › PHP Enums

PHP Enums

Many values in a program can only be one of a small, fixed set: an order status, a card suit, a day of the week. Before PHP 8.1 people used strings or class constants for these, which allowed typos like "shiped" to slip through. Enumerations (enums) make the set of allowed values a real type, checked by PHP.

A pure enum

php · try it yourself
<?php
enum Suit
{
    case Hearts;
    case Diamonds;
    case Clubs;
    case Spades;
}

function colour(Suit $s): string
{
    return match ($s) {
        Suit::Hearts, Suit::Diamonds => "red",
        Suit::Clubs, Suit::Spades => "black",
    };
}

$card = Suit::Diamonds;
echo $card->name, " is ", colour($card), "\n";

var_dump($card === Suit::Diamonds);
var_dump($card instanceof Suit);
echo count(Suit::cases()), " suits\n";
Diamonds is red
bool(true)
bool(true)
4 suits

Each case is a singleton object: Suit::Diamonds === Suit::Diamonds is always true. The name property holds the case name as a string, and cases() returns all cases in declaration order.

Tip: match and enums are a perfect pair. If you forget a case, match throws an UnhandledMatchError instead of silently doing nothing.

Backed enums

A backed enum gives every case a scalar value — int or string — which is what you store in a database or send as JSON.

php · try it yourself
<?php
enum Status: string
{
    case Draft = 'draft';
    case Published = 'published';
    case Archived = 'archived';
}

echo Status::Published->value, "\n";

$fromDb = Status::from('archived');
echo $fromDb->name, "\n";

$maybe = Status::tryFrom('deleted');
var_dump($maybe);

try {
    Status::from('deleted');
} catch (ValueError $e) {
    echo get_class($e), ": ", $e->getMessage(), "\n";
}

echo json_encode(['status' => Status::Draft]), "\n";
published
Archived
NULL
ValueError: "deleted" is not a valid backing value for enum Status
{"status":"draft"}
Method / property Pure enum Backed enum
->name yes yes
->value no yes
::cases() yes yes
::from($v) no yes — throws ValueError if unknown
::tryFrom($v) no yes — returns null if unknown

Methods, interfaces and constants

Enums can have methods (including static ones), implement interfaces and declare constants. They cannot have properties that change, and you cannot create them with new.

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

enum OrderStatus: int implements HasLabel
{
    case Pending = 1;
    case Shipped = 2;
    case Delivered = 3;
    case Cancelled = 9;

    const DEFAULT = self::Pending;

    public function label(): string
    {
        return match ($this) {
            self::Pending => '⏳ Waiting for payment',
            self::Shipped => '🚚 On its way',
            self::Delivered => '✅ Delivered',
            self::Cancelled => '❌ Cancelled',
        };
    }

    public function isFinal(): bool
    {
        return $this === self::Delivered || $this === self::Cancelled;
    }

    public static function active(): array
    {
        return array_filter(self::cases(), fn($s) => !$s->isFinal());
    }
}

foreach (OrderStatus::cases() as $s) {
    printf("%-9s %d %s%s\n", $s->name, $s->value, $s->label(), $s->isFinal() ? " (final)" : "");
}

echo "Default: ", OrderStatus::DEFAULT->name, "\n";
echo "Active: ", implode(", ", array_map(fn($s) => $s->name, OrderStatus::active())), "\n";
Pending   1 ⏳ Waiting for payment
Shipped   2 🚚 On its way
Delivered 3 ✅ Delivered (final)
Cancelled 9 ❌ Cancelled (final)
Default: Pending
Active: Pending, Shipped

Enums as type-safe parameters

Because an enum is a type, a function can demand exactly one of its cases. Passing a plain string is rejected with a TypeError.

php · try it yourself
<?php
enum Size: string
{
    case Small = 'S';
    case Medium = 'M';
    case Large = 'L';

    public function price(): float
    {
        return match ($this) {
            self::Small => 2.50,
            self::Medium => 3.20,
            self::Large => 3.90,
        };
    }
}

function order(string $drink, Size $size): string
{
    return "$drink ({$size->value}) costs " . number_format($size->price(), 2);
}

echo order("Latte", Size::Large), "\n";
echo order("Tea", Size::from('S')), "\n";

try {
    echo order("Mocha", 'M');
} catch (TypeError $e) {
    echo "TypeError caught\n";
}
Latte (L) costs 3.90
Tea (S) costs 2.50
TypeError caught

Note: Enum cases are objects but not regular class instances: you cannot clone them, add properties, or compare them with < and >. Compare with ===, or compare their ->value when you need ordering.

Test yourself

Which method returns null instead of throwing when the value is unknown?

  1. from()
  2. tryFrom()
  3. cases()
  4. value()

What does Suit::cases() return?

  1. The number of cases
  2. An array of all case objects in declaration order
  3. An array of case names as strings
  4. The first case

Which property exists only on backed enums?

  1. name
  2. value
  3. cases
  4. class