PHP enums header

The problem: magic strings everywhere

A common backend pattern is to store a “state” as a string in the database and sprinkle the same literals across your code:

// order status stored as VARCHAR in the DB
if ($row['status'] === 'shipped') { /* ... */ }
$order->status = 'shipped';
throw new \Exception('unknown status: ' . $status);

This compiles, but it will happily accept 'shiped', 'SHIPPED', or 'pendingg' and fail ten files away from where the typo was introduced. There is no single source of truth, and your IDE cannot help you.

The fix: a backed enum

PHP 8.1+ gives you enums. A backed enum maps each case to a scalar value (usually a string that matches what you already store in the DB):

enum OrderStatus: string
{
    case Pending   = 'pending';
    case Paid      = 'paid';
    case Shipped   = 'shipped';
    case Cancelled = 'cancelled';
}

Now the allowed values live in exactly one place, and $status instanceof OrderStatus is type-checked at compile time.

Parsing untrusted input: from() vs tryFrom()

When the value comes from the database, a form, or an API request, you must turn a raw string into an enum. Use from() and tryFrom():

// from() throws ValueError on an invalid value — good when you trust the source
$status = OrderStatus::from($row['status']);

// tryFrom() returns null instead of throwing — safe for untrusted user input
$status = OrderStatus::tryFrom($_POST['status']); // null if "shiped"
if ($status === null) {
    http_response_code(400);
    echo 'Invalid status';
    return;
}

Rule of thumb: from() for data you control (DB rows you wrote), tryFrom() for anything a client sent.

The gotcha: enums are singletons, not their values

A frequent bug is comparing an enum to its scalar by mistake:

$status = OrderStatus::Shipped;

$status === 'shipped';               // false — you compared an object to a string
$status === OrderStatus::Shipped;    // true  — identity comparison
$status->value === 'shipped';        // true  — read the ->value explicitly

Because each case is a single instance, === between two enum values is an identity check (and == works too here). Always read ->value when you need the stored scalar — for JSON output, DB writes, or comparisons against raw strings.

Bonus: enums in match() and as keys

match() pairs beautifully with enums and is exhaustiveness-checked by the compiler:

$label = match ($status) {
    OrderStatus::Pending   => 'Awaiting payment',
    OrderStatus::Paid      => 'Paid, not yet shipped',
    OrderStatus::Shipped   => 'On the way',
    OrderStatus::Cancelled => 'Cancelled',
};

Optional backed methods keep domain logic next to the data:

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

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

if ($order->status->isFinal()) {
    // nothing more to do
}

Takeaway

  • Backed enums replace magic strings with a single, typed source of truth.
  • from() throws, tryFrom() returns null — pick based on who supplied the value.
  • Compare enums with === (identity), and use ->value when you need the scalar.
  • match() + enums gives you exhaustiveness checking for free.