Table of Contents

7. Enums — Giving Meaningful Shape to Known Values

Enums solve one of the oldest problems in PHP:
representing a closed set of meaningful values without magic strings or loose integers.
Enums are one of the most expressive additions to modern PHP.
They let us represent a closed set of values with clarity, type safety, and intention
— without relying on magic strings, integers, or scattered constants.

They reflect a broader shift in PHP 8.1+:
values should have
shape, meaning,
and a home
.


1. What Enums Are

Enums define a fixed set of possible values.
Each value is a real object with identity, type, and meaning.

enum Status {
    case Draft;
    case Published;
    case Archived;
}

No strings.
No integers.
No guessing.

Just clear, intentional values.


2. Why Modern PHP Uses Them

Enums give us:-type safety,
-self‑documenting code,
-predictable value sets,
-fewer runtime surprises,
-a single source of truth

They replace:

Enums make the domain more explicit
— and easier for both humans and AI to understand.


3. The Mental Model

Enums are named values with identity.

Each enum case is a real object
that represents a meaningful state in our domain.

The key idea:

Use enums when a value has meaning,
not just content
.


4. A Simple Example

enum Role {
    case Admin;
    case Editor;
    case Viewer;
}
 
function canEdit(Role $role): bool
{
    return match ($role) {
        Role::Admin, Role::Editor => true,
        Role::Viewer => false,
    };
}

The code becomes clearer because the values themselves carry intent.


5. Backed Enums

Sometimes we need to store or transmit the value.
Backed enums give each case a scalar representation:

enum Currency: string {
    case USD = 'usd';
    case EUR = 'eur';
    case GBP = 'gbp';
}

You get the best of both worlds:


6. When to Use Enums

Use enums when:

Enums shine in DTOs, domain models, controllers, and API boundaries.


7. When Not to Use Enums

Avoid enums when:

Enums are for meaningful values, not dynamic data.


When AI Gets This Wrong

AI often invents enum cases that don’t exist, mixes backed and unbacked enums, or uses enums where a simple string is more appropriate.
Sometimes it treats enums as if they should contain behavior, or nests enums inside enums.

Our mental model helps us see when an enum expresses real meaning
— and when AI is using one simply because it “looks structured”.


Summary

Enums give shape to meaningful values.
They replace magic strings, reduce ambiguity,
and make the domain more explicit.

Once we internalize this,
we can immediately see when AI‑generated code:

Enums are a small feature
— but they teach us how modern PHP wants to express identity and intention.