Enumerations

Enumerations in PHP: --- An industrial washing machine does not have a free-text box where the operator types the wash program.


The Analogy: The Machine's Labelled Selector Dial

An industrial washing machine does not have a free-text box where the operator types the wash program. It has a selector dial with a fixed set of labelled positions: Cottons, Delicates, Wool, Spin. The dial physically cannot point anywhere else -- there is no gap between Wool and Spin where an operator could invent a program the machine does not have. This constraint is the whole point: by limiting the choices to a known, closed set, the dial makes an invalid selection impossible. An enumeration is that selector dial. Instead of passing around a bare string 'wool' that could be misspelled 'woll', you pass an enum case that can only ever be one of the defined values.

Because the positions are fixed and named, everyone who works with the machine shares the same vocabulary. A repair technician, the operator, and the instruction manual all refer to "the Wool position", not to some ad hoc string that one person spells one way and another spells differently. An enum gives your code this shared, typo-proof vocabulary: Status::Published is one specific thing the compiler and every reader agree on, where a loose string 'published' might elsewhere be written 'Published' or 'pub' and silently fail to match.

The dial can also carry behaviour tied to each position. Turn to Delicates and the machine automatically selects a low spin speed and cool water; the position is not just a label but a bundle of associated properties and rules. Enums in PHP can hold methods, so Severity::Critical can answer "what is your escalation weight?" directly. The valid choices and the logic that depends on them live together, rather than the logic being scattered across distant if statements that each re-interpret a raw string.

The failure mode is the machine someone has modified to accept a typed-in program code, bypassing the dial. Now an operator can enter WOOL2, spin, or an empty string, and the machine either does something unintended or fails obscurely deep in a cycle. In code this is the "stringly-typed" system where a status is just a string passed everywhere: every function must defensively re-validate it, a typo passes silently until it causes a wrong branch far away, and there is no single list of what the valid values even are. The enum exists precisely to make the invalid unrepresentable -- and the moment you route around it with raw strings, you inherit every bug the dial was designed to prevent.


Syntax or Core Structure

PHP 8.1 introduced enums. A pure enum is a set of named cases; a backed enum gives each case a scalar value, enabling conversion to and from that value with from and tryFrom.

<?php
declare(strict_types=1);

enum Direction {
    case North;
    case East;
    case South;
    case West;
}

$d = Direction::East;
echo 'name: ', $d->name, "\n";
echo 'is East: ', ($d === Direction::East ? 'yes' : 'no'), "\n";
echo 'count: ', count(Direction::cases()), "\n";

enum Status: string {
    case Draft = 'draft';
    case Published = 'published';
    case Archived = 'archived';
}

$s = Status::from('published');
echo 'from value: ', $s->name, "\n";
echo 'value of Draft: ', Status::Draft->value, "\n";
echo 'tryFrom bad: ', var_export(Status::tryFrom('nope'), true), "\n";

Output:

name: East
is East: yes
count: 4
from value: Published
value of Draft: draft
tryFrom bad: NULL

The pure Direction enum exposes each case's name, compares by identity, and lists every case with cases() -- here four. The backed Status enum attaches a string value to each case: from('published') returns the matching Published case, Status::Draft->value reads its backing string draft, and tryFrom('nope') returns null for an unknown value rather than throwing (which from would). Backed enums are the bridge between your typed cases and the raw values stored in a database or sent over the wire.


Technical Depth: Methods, Interfaces, and Pure vs Backed

Pure versus backed enums

The two kinds serve different needs. A pure enum is a closed set of identities with no inherent scalar; a backed enum maps each case to a string or int for persistence and transport.

AspectPure enumBacked enum
Case has a valueNoYes (string or int)
->valueNot availableThe backing scalar
from / tryFromNot availableConvert from scalar
Use forIn-memory statesValues stored or transmitted

Both support cases(), methods, constants, and implementing interfaces. Choose backed when the value must round-trip through a database, JSON, or a form; choose pure when the cases exist only in code.

Methods and match

Enums can hold methods, letting behaviour that depends on the case live inside the enum. A match on $this is the idiomatic way to map each case to a result.

<?php
declare(strict_types=1);

enum Suit: string {
    case Hearts = 'H';
    case Diamonds = 'D';
    case Clubs = 'C';
    case Spades = 'S';

    public function color(): string {
        return match ($this) {
            Suit::Hearts, Suit::Diamonds => 'red',
            Suit::Clubs, Suit::Spades => 'black',
        };
    }
    public function label(): string {
        return ucfirst(strtolower($this->name)) . ' (' . $this->value . ')';
    }
}

foreach (Suit::cases() as $suit) {
    echo $suit->label(), ': ', $suit->color(), "\n";
}

Output:

Hearts (H): red
Diamonds (D): red
Clubs (C): black
Spades (S): black

Each Suit case carries a one-letter backing value, and color uses match ($this) to group the red and black suits -- note a single arm can list several cases. label combines the case name and value into a display string. Iterating cases() walks all four in declaration order. Because the match covers every case and would error if one were missing, adding a fifth suit later forces you to handle it -- the compiler-enforced exhaustiveness a raw string could never give.

Implementing an interface

An enum can implement an interface, so it fits anywhere that contract is expected -- useful for giving a family of enums a shared capability.

<?php
declare(strict_types=1);

interface HasPriority {
    public function weight(): int;
}

enum Severity: string implements HasPriority {
    case Low = 'low';
    case Medium = 'medium';
    case High = 'high';
    case Critical = 'critical';

    public function weight(): int {
        return match ($this) {
            Severity::Low => 1,
            Severity::Medium => 5,
            Severity::High => 10,
            Severity::Critical => 20,
        };
    }
}

$incidents = [Severity::Medium, Severity::Critical, Severity::Low, Severity::High];
usort($incidents, fn(Severity $a, Severity $b) => $b->weight() <=> $a->weight());
foreach ($incidents as $s) {
    echo $s->value, ' = ', $s->weight(), "\n";
}

Output:

critical = 20
high = 10
medium = 5
low = 1

Severity implements HasPriority, so its weight method satisfies the interface and any code expecting a HasPriority accepts a Severity. Sorting the incidents by weight descending with the spaceship operator orders them critical to low. The enum bundles the valid severities and their relative weights in one place, so the ordering logic cannot disagree with the set of allowed values.


Real World Example: An Order State Machine

Order status is a classic place where stringly-typed code rots. An order moves through a fixed set of states, and only certain transitions are legal: a pending order can be paid or cancelled, a paid order can ship or be cancelled, a shipped order can be delivered, and a delivered order is done. Modelling the states as an enum -- and the legal moves as a method on that enum -- puts the rules where the states live.

<?php
declare(strict_types=1);

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

    /** @return list<OrderState> */
    public function allowedNext(): array {
        return match ($this) {
            OrderState::Pending => [OrderState::Paid, OrderState::Cancelled],
            OrderState::Paid => [OrderState::Shipped, OrderState::Cancelled],
            OrderState::Shipped => [OrderState::Delivered],
            OrderState::Delivered, OrderState::Cancelled => [],
        };
    }

    public function canTransitionTo(OrderState $next): bool {
        return in_array($next, $this->allowedNext(), true);
    }

    public function isTerminal(): bool {
        return $this->allowedNext() === [];
    }
}

$check = function (OrderState $from, OrderState $to): void {
    $verb = $from->canTransitionTo($to) ? 'ok' : 'no';
    echo $from->name, ' -> ', $to->name, ': ', $verb, "\n";
};

$check(OrderState::Pending, OrderState::Paid);
$check(OrderState::Pending, OrderState::Shipped);

echo 'Delivered -> anything: ',
    (OrderState::Delivered->isTerminal() ? 'terminal' : 'open'), "\n";

$names = array_map(fn(OrderState $s) => $s->value, OrderState::Paid->allowedNext());
echo 'Paid allowed next: ', implode(', ', $names), "\n";

Output:

Pending -> Paid: ok
Pending -> Shipped: no
Delivered -> anything: terminal
Paid allowed next: shipped, cancelled

The OrderState enum names the five states once, and allowedNext reads as a transition table: each case maps to the list of states it may move to, with the two terminal states mapping to an empty array. canTransitionTo reuses that table via a strict in_array, and isTerminal derives its answer from the same source rather than repeating the list. The strict comparison is safe because enum cases are singletons -- OrderState::Paid is identical to itself everywhere in the program.

The first check confirms a pending order may be paid; the second rejects the illegal jump straight to shipped, because Shipped is not in Pending's allowed list. Asking whether Delivered is terminal returns true, since its allowed-next list is empty. The last line maps Paid's allowed transitions back to their string values, printing shipped, cancelled -- exactly the moves a paid order is permitted.

Because the states and the transition rules live inside one enum, a stray string like 'payed' can never enter the system, and match forces you to define allowedNext for any new case you add. Compared with a bare string column and scattered if checks, the intent is centralised and the illegal states are simply unrepresentable.

The design flaw is that the enum guarantees each individual state is valid and that canTransitionTo reports the rules, but nothing forces callers to consult those rules. A careless service could write $order->state = OrderState::Delivered directly, skipping canTransitionTo entirely, and the enum could not stop it -- the type system knows the set of states but not the order they must occur in. Enforcing the sequence needs a wrapper (a setter that calls canTransitionTo and throws on an illegal move), because a value type cannot police how it is assigned.


Common Mistakes

  1. Calling from or tryFrom on a pure enum. These methods exist only on backed enums. A pure enum has no scalar to convert from, so Direction::from('N') is a fatal error. If you need to build a case from an external value, declare the enum backed.
  1. Using from with untrusted input. Status::from($_GET['s']) throws a ValueError the moment the value is not a valid case, crashing the request. For anything that comes from outside the program, use tryFrom and handle the null.
  1. Comparing ->value instead of the case. Writing if ($order->state->value === 'paid') throws away the type safety the enum gave you and reintroduces the magic string. Compare the case itself: if ($order->state === OrderState::Paid).
  1. Expecting new to work. Enum cases are not constructed with new Suit(...); they are referenced as constants like Suit::Hearts. Trying to instantiate an enum is a fatal error, because every case is a fixed singleton.
  1. Declaring properties with state. An enum may have methods and constants but not mutable instance properties -- public int $count = 0; inside an enum is illegal. Cases are immutable shared singletons, so per-instance state has nowhere to live.
  1. A non-exhaustive match on $this. If match ($this) omits a case and no default is given, the missing case throws UnhandledMatchError at runtime. Either handle every case explicitly, which turns a forgotten branch into a hard error you notice immediately, or add a deliberate default.
  1. Non-strict in_array with cases. in_array($case, $list) without the third true argument uses loose comparison and can misbehave. Always pass true so enum cases are compared by identity, as in in_array($next, $this->allowedNext(), true).
  1. Assuming json_encode serialises a pure enum. Encoding a backed enum yields its scalar value, but a pure enum has no scalar and json_encode throws. If a value must appear in JSON, back it -- or implement JsonSerializable to decide the representation.
  1. Duplicate backing values. Two cases with the same backing value, such as case A = 'x' and case B = 'x', is a fatal error at load time. Each backing value must be unique so from and tryFrom map unambiguously to one case.

Best Practices

  • Reach for an enum whenever a variable should hold one of a small, fixed set of named values -- states, roles, suits, severities. It replaces loose strings and int constants with a checked type.
  • Prefer a backed enum when the value is stored in a database, sent over the wire, or read from a form, so it round-trips cleanly. Use a pure enum when the cases exist only inside the program.
  • Use tryFrom for any value that originates outside your code and handle the null branch explicitly; reserve from for values you already know are valid.
  • Put case-dependent behaviour in methods on the enum with match ($this), keeping the logic beside the cases it describes instead of scattering switch statements across the codebase.
  • Let match be exhaustive rather than adding a catch-all default. An unhandled case then fails loudly the instant you add a new one, pointing you straight at the code to update.
  • Give an enum an interface when several enums share a capability, so callers depend on the contract (HasPriority) rather than the concrete enum.
  • Compare cases by identity (=== or strict in_array) and never by their backing value, so the type checking the enum provides is not quietly discarded.
  • Iterate cases() to drive menus, validation lists, and seed data from the single source of truth, so adding a case updates every derived list automatically.

Practice Exercises

  1. Define a backed enum HttpMethod: string with cases Get, Post, Put, Delete. Add an isSafe(): bool method returning true only for Get, and print each method with its safety using a cases() loop.
  1. Create a pure enum Weekday with the seven days and a method isWeekend(): bool. Write a function that takes a Weekday and returns 'rest' or 'work', and demonstrate it without using any string literals for the days.
  1. Build a TrafficLight backed enum (Red, Amber, Green) with a next(): self method that cycles Red -> Green -> Amber -> Red. Print three transitions starting from Red to prove the cycle.
  1. Extend the OrderState machine: add a method transitionTo(OrderState $next): OrderState that returns the new state when the move is legal and throws an InvalidArgumentException naming both states when it is not. Show one successful and one rejected transition.