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.
| Aspect | Pure enum | Backed enum |
|---|---|---|
| Case has a value | No | Yes (string or int) |
->value | Not available | The backing scalar |
from / tryFrom | Not available | Convert from scalar |
| Use for | In-memory states | Values 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
- Calling
fromortryFromon a pure enum. These methods exist only on backed enums. A pure enum has no scalar to convert from, soDirection::from('N')is a fatal error. If you need to build a case from an external value, declare the enum backed.
- Using
fromwith untrusted input.Status::from($_GET['s'])throws aValueErrorthe moment the value is not a valid case, crashing the request. For anything that comes from outside the program, usetryFromand handle thenull.
- Comparing
->valueinstead of the case. Writingif ($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).
- Expecting
newto work. Enum cases are not constructed withnew Suit(...); they are referenced as constants likeSuit::Hearts. Trying to instantiate an enum is a fatal error, because every case is a fixed singleton.
- 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.
- A non-exhaustive
matchon$this. Ifmatch ($this)omits a case and nodefaultis given, the missing case throwsUnhandledMatchErrorat runtime. Either handle every case explicitly, which turns a forgotten branch into a hard error you notice immediately, or add a deliberatedefault.
- Non-strict
in_arraywith cases.in_array($case, $list)without the thirdtrueargument uses loose comparison and can misbehave. Always passtrueso enum cases are compared by identity, as inin_array($next, $this->allowedNext(), true).
- Assuming
json_encodeserialises a pure enum. Encoding a backed enum yields its scalar value, but a pure enum has no scalar andjson_encodethrows. If a value must appear in JSON, back it -- or implementJsonSerializableto decide the representation.
- Duplicate backing values. Two cases with the same backing value, such as
case A = 'x'andcase B = 'x', is a fatal error at load time. Each backing value must be unique sofromandtryFrommap 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
tryFromfor any value that originates outside your code and handle thenullbranch explicitly; reservefromfor 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 scatteringswitchstatements across the codebase.
- Let
matchbe exhaustive rather than adding a catch-alldefault. 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 strictin_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
- Define a backed enum
HttpMethod: stringwith casesGet,Post,Put,Delete. Add anisSafe(): boolmethod returning true only forGet, and print each method with its safety using acases()loop.
- Create a pure enum
Weekdaywith the seven days and a methodisWeekend(): bool. Write a function that takes aWeekdayand returns'rest'or'work', and demonstrate it without using any string literals for the days.
- Build a
TrafficLightbacked enum (Red,Amber,Green) with anext(): selfmethod that cycles Red -> Green -> Amber -> Red. Print three transitions starting fromRedto prove the cycle.
- Extend the
OrderStatemachine: add a methodtransitionTo(OrderState $next): OrderStatethat returns the new state when the move is legal and throws anInvalidArgumentExceptionnaming both states when it is not. Show one successful and one rejected transition.