← Tous les articles

PHP 8.1 enums: stop storing statuses as loose strings

“paid”, “Paid” and “payed” in the same column? PHP 8.1 enums make those values impossible. How to use them, store them, and avoid the usual traps.

PHP 8.1 enums: stop storing statuses as loose strings

Key points

  • An enum turns a bag of constants into a type PHP checks for you.
  • Backed enums go into the database and JSON through their value.
  • tryFrom() and match surface unknown cases instead of hiding them.

On one application we took over, the orders status column held paid, Paid, payed and completed — the last one meaning the same thing, depending on who wrote the code. Every report was off. That drift is what happens when statuses are just strings passed around. Since PHP 8.1, enums fix it at the language level.

An enum that earns its keep

A backed enum maps each case to a scalar, which is what you store. You can add methods, so the related logic lives in one place:

enum OrderStatus: string
{
    case Pending  = 'pending';
    case Paid     = 'paid';
    case Refunded = 'refunded';

    public function label(): string
    {
        return match ($this) {
            self::Pending  => 'Pending',
            self::Paid     => 'Paid',
            self::Refunded => 'Refunded',
        };
    }

    public function canRefund(): bool
    {
        return $this === self::Paid;
    }
}

A function typed function ship(OrderStatus $s) can no longer receive a misspelled string. The mistake fails on the first call, not three weeks later in a spreadsheet.

Reading from and writing to the database

Store $status->value and read it back with from() or tryFrom(). The difference matters: from() throws a ValueError on an unknown value, tryFrom() returns null.

$status = OrderStatus::tryFrom($row['status'])
    ?? throw new UnexpectedValueException("Unknown status: {$row['status']}");

When we move a legacy app to enums, step one is a SELECT DISTINCT status to see what is really in the table, then we clean the data before wiring in the enum. Skip that and the first page that loads an old row breaks in production. Laravel casts the column for you with 'status' => OrderStatus::class in $casts; Doctrine has an enumType option.

Gotchas we keep running into

  • Not usable as array keys: an enum case is an object. Key by $status->value, or use a WeakMap.
  • Pure enums (no backing value) make json_encode() throw. For anything that leaves your app through an API, use backed enums, which encode as their value.
  • A match with no default is a feature: add a new case and an UnhandledMatchError points straight at every place you forgot. Do not add a default out of habit.
  • Compare cases with ===, not by comparing strings: $order->status === OrderStatus::Paid.

Feeding a form

OrderStatus::cases() returns every case in declaration order. For a select field: array_map(fn($c) => [$c->value, $c->label()], OrderStatus::cases()). Form, validation and display now share one source of truth.

FAQ

Can I use enums in a WordPress plugin?

Yes, as long as you declare Requires PHP: 8.1 in the plugin header. For a widely distributed plugin, check what PHP versions your users actually run first.

Should the database enforce it too?

It is a worthwhile extra guard: an ENUM type or a CHECK constraint stops a SQL script or another tool from writing a value PHP would reject.

Is your app collecting inconsistent data? We audit and modernise PHP codebases step by step, without downtime.

Partager LinkedIn Facebook X WhatsApp
</>

webtestudio

Agence web : sites WordPress sur mesure, thèmes premium et logiciels SaaS.

Parler de votre projet →