Enums

2.Enums

M

In this chapter

We'll learn enums — PHP's type for "one of a fixed set of values" — how pure and backed enums differ, how from() and tryFrom() turn database strings into cases, how enums get methods, constants and interfaces, how they're stored and sent as JSON — and how they compare with Java enums with fields, Rust and Swift enums with associated values, and TypeScript union types.

18–20 min

The Problem in Real Life

The weekly report says Tom had 41 confirmed bookings. The bank says 44 were paid. Mia finds the three missing ones: their status is "confirmd", "Confirmed" and "CONFIRMED". Three different scripts wrote the status, each in its own way, and the report counts only === "confirmed".

"A status isn't any string," says Marcus. "It's one of exactly three things. PHP can know that."

O

"confirmd" should be impossible. Not unlikely — impossible.

Olivia

Magic Strings vs. a Fixed Set of Cases

Magic strings

"confirmed" typed by hand in 30 places. Every typo is a new, silent status that no rule knows about.

Only real cases

A BookingStatus parameter accepts Pending, Confirmed or Cancelled — nothing else, checked by PHP.

To the database and back

Backed enums map each case to a string or int for storage, and back with from() and tryFrom().

Enums

A type with a fixed list of values: an enum (short for enumeration) is a type whose values are a fixed, named list, called cases. PHP has had them since 8.1. This chapter covers:

  • Pure enums: cases with names only.
  • Backed enums: cases with a string or int value, for databases and JSON.
  • Methods, constants and interfaces: enums that know about themselves.
  • Enums in other languages: fields (Java), associated values (Rust, Swift), unions (TypeScript) — and where PHP stands.

Pure enums: enum BookingStatus { case Pending; case Confirmed; case Cancelled; } declares a type with exactly three values: BookingStatus::Pending, BookingStatus::Confirmed and BookingStatus::Cancelled. A property or parameter typed BookingStatus can hold nothing else, so "confirmd" is impossible — a typo in a case name is an error the moment the code runs, and your editor sees it before. Each case is a singleton: there's exactly one BookingStatus::Confirmed object, so === compares cases. You can't create cases with new. ->name gives a case's name as a string, and BookingStatus::cases() lists all of them in order.

Mia's bug, and a pure enum
<?php
declare(strict_types=1);
$statuses = ["confirmed", "confirmd", "Confirmed", "CONFIRMED", "pending"];
echo count(array_filter($statuses, fn($s) => $s === "confirmed")), " counted as confirmed\n";
// 1 counted as confirmed — three bookings lost
enum BookingStatus
{
case Pending;
case Confirmed;
case Cancelled;
}
function isPaid(BookingStatus $status): bool
{
return $status === BookingStatus::Confirmed; // one object per case: === works
}
var_dump(isPaid(BookingStatus::Confirmed)); // bool(true)
echo BookingStatus::Confirmed->name, "\n"; // Confirmed
echo count(BookingStatus::cases()), " cases\n"; // 3 cases
// BookingStatus::Confirmd → Error: Undefined constant BookingStatus::Confirmd

Backed enums: a database column or a JSON field can't hold a PHP object; it needs a string or a number. A backed enum gives every case a fixed value of one type: enum BookingStatus: string { case Pending = "pending"; case Confirmed = "confirmed"; ... }. ->value gives the stored value. To go back, BookingStatus::from("confirmed") returns the case, and throws a ValueError for an unknown value like "confirmd"; tryFrom() returns null instead. Use from() where a wrong value is a bug, and tryFrom() for input that may be wrong, like a form or an old database row. json_encode() writes a backed case as its value; pure enums can't be turned into JSON at all. The diagram below follows a status from the database into PHP and back.

A backed enum's round trip

Database row

status = 'confirmed'

reading

BookingStatus::from('confirmed')

→ BookingStatus::Confirmed

BookingStatus::tryFrom('confirmd')

→ null (bad data)

in the program

PHP code works with the case

$booking->status === BookingStatus::Confirmed

writing

->value / json_encode()

'confirmed' back to the database or the API

A backed enum: to the database and back
<?php
declare(strict_types=1);
enum BookingStatus: string
{
case Pending = "pending";
case Confirmed = "confirmed";
case Cancelled = "cancelled";
}
$fromDb = BookingStatus::from("confirmed"); // the row's value → a case
var_dump($fromDb === BookingStatus::Confirmed); // bool(true)
echo BookingStatus::Cancelled->value, "\n"; // cancelled: what you store
var_dump(BookingStatus::tryFrom("confirmd")); // NULL: bad input, no exception
try {
BookingStatus::from("confirmd");
} catch (ValueError $e) {
echo $e->getMessage(), "\n";
}
echo json_encode(["status" => BookingStatus::Confirmed]), "\n";
// "confirmd" is not a valid backing value for enum BookingStatus
// {"status":"confirmed"}

Methods, constants and interfaces: enums can have methods, and inside them $this is the current case: a label() method with return match ($this) { self::Pending => "Waiting", ... }; puts every status's display text in one place. Because match without default throws on a missing case (Act 06), adding a fourth status later makes PHP point at every match you forgot to update. Enums can also have static methods (named constructors, chapter 3 of Act 11), constants (which may refer to cases: const DEFAULT = self::Pending;), implement interfaces, and use traits — as long as the trait has no properties. What enums can't have is properties or state: a case is a constant, not a container ("Enum … cannot include properties"). That's what keeps every case a true singleton.

Methods, constants and an interface
<?php
declare(strict_types=1);
interface HasLabel
{
public function label(): string;
}
enum BookingStatus: string implements HasLabel
{
case Pending = "pending";
case Confirmed = "confirmed";
case Cancelled = "cancelled";
public const DEFAULT = self::Pending;
public function label(): string
{
return match ($this) { // no default: a new case can't be forgotten
self::Pending => "Waiting for confirmation",
self::Confirmed => "Confirmed",
self::Cancelled => "Cancelled",
};
}
public function canBeConfirmed(): bool
{
return $this === self::Pending;
}
}
echo BookingStatus::DEFAULT->label(), "\n"; // Waiting for confirmation
var_dump(BookingStatus::Cancelled->canBeConfirmed()); // bool(false)
var_dump(BookingStatus::Confirmed instanceof HasLabel); // bool(true)
Enums can't have properties or be created with new
<?php
enum BookingStatus
{
case Pending;
public string $reason;
}
// Fatal error: Enum BookingStatus cannot include properties
// (and new BookingStatus() → Error: Cannot instantiate enum BookingStatus)

Enums with fields and constructors — not in PHP: Java's enums are full classes: each case can carry fields set by a constructor, like CONFIRMED("Confirmed", true). PHP doesn't support properties or constructors on enums. The PHP way is a method that answers from the case: public function isFinal(): bool { return match ($this) { ... }; }. It's a few more lines, but the data is still fixed per case, as in Java.

Java: an enum with fields and a constructor (not in PHP)
// Java — each case carries data set by the enum's constructor
enum BookingStatus {
PENDING("Waiting for confirmation", false),
CONFIRMED("Confirmed", true),
CANCELLED("Cancelled", true);
private final String label;
private final boolean isFinal;
BookingStatus(String label, boolean isFinal) {
this.label = label;
this.isFinal = isFinal;
}
String label() { return label; }
}
// PHP: no enum properties or constructors — answer from the case with match ($this).

Associated values — not in PHP: in Rust and Swift, each case of an enum can carry its own data, different for every value: Cancelled { reason: String } or case cancelled(reason: String). These are called algebraic data types, or tagged unions, and the compiler checks that every case is handled. PHP doesn't support associated values: every use of BookingStatus::Cancelled is the same object, with no room for a reason. In PHP, put the extra data next to the enum — a ?string $cancelReason property on Booking — or model each kind as its own small class implementing one interface.

Rust: associated values (not in PHP)
// Rust — each value of a case carries its own data
enum BookingStatus {
Pending,
Confirmed { paid_pence: u32 },
Cancelled { reason: String },
}
fn describe(s: &BookingStatus) -> String {
match s { // the compiler checks every case is handled
BookingStatus::Pending => "waiting".to_string(),
BookingStatus::Confirmed { paid_pence } => format!("paid {paid_pence}p"),
BookingStatus::Cancelled { reason } => format!("cancelled: {reason}"),
}
}
// PHP: BookingStatus::Cancelled is one shared object — keep the reason in a Booking property.

Union types, sets and maps of enums: TypeScript often uses string union types instead of enums: type Status = "pending" | "confirmed". PHP's backed enum does the same job with a real type behind it. Java also has EnumSet and EnumMap, fast collections keyed by enum cases. PHP doesn't have them; use an array keyed by ->value (or ->name), or WeakMap, which can use the case objects themselves as keys. The table below compares PHP's enums with the other languages.

Table — Enums compared
FeaturePHPOther languages
Fixed set of named casesenum Status { case A; }Java, C#, Rust, Swift, TypeScript
A stored value per caseBacked enum: case A = "a"Java: fields; C#: int values; TS: string enums
Methods on casesYes, with match ($this)Java, Rust, Swift: yes
Fields and a constructorNo: use methodsJava: yes
Different data per valueNo: put it in a property or a classRust, Swift: associated values
Sets and maps of casesNo: arrays keyed by ->value, WeakMapJava: EnumSet, EnumMap
Every case handled?match without default throws at runtimeRust, Swift: checked by the compiler
A map of cases: an array keyed by ->value
<?php
declare(strict_types=1);
enum BookingStatus: string
{
case Pending = "pending";
case Confirmed = "confirmed";
case Cancelled = "cancelled";
}
$day = [BookingStatus::Confirmed, BookingStatus::Pending, BookingStatus::Confirmed];
$counts = array_fill_keys(array_map(fn($s) => $s->value, BookingStatus::cases()), 0);
foreach ($day as $status) {
$counts[$status->value]++;
}
print_r($counts);
// Array
// (
// [pending] => 1
// [confirmed] => 2
// [cancelled] => 0
// )

Key Takeaway

An enum is a type with a fixed set of cases, so impossible values like "confirmd" can't exist. Pure enums have names only; backed enums give each case a string or int ->value, converted back with from() (ValueError on bad input) or tryFrom() (null). Enums can have methods (use match ($this)), static methods, constants and interfaces, but no properties, constructors or new. PHP has no enum fields (Java), no associated values (Rust, Swift) and no EnumSet/EnumMap; use methods, separate properties or classes, and arrays keyed by ->value.

Why This Matters

Statuses, payment methods, roles, notification channels: every business has small, fixed sets of values, and as strings they're typed by hand in dozens of places. Enums turn every one of those places into checked code, and the "unknown status" bug becomes impossible.

Enums are also one of the most used modern PHP features: Laravel casts database columns to enums, validates request fields against them, and uses them in routes. Knowing what they can't do — no properties, no per-value data — tells you when to reach for a class instead.

Booking::$status is a BookingStatus now, rows are read with tryFrom(), and the three lost bookings are fixed by hand. Next, Mia writes tests for the confirmation code, each with its own small fake notifier class. The second test file stops PHP with "Cannot redeclare class FakeNotifier": both files declared one. A class used in exactly one place shouldn't need a name at all. That's the next chapter: anonymous classes and final.