×

php · level 3 · unit 3 · lesson 3

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

A gives every case a value you can save.

Databases and forms speak in strings, not enum cases. A backed enum gives each case a fixed value: enum Status: string, with case Shipped = "shipped";. Read it with ->value when you save, and turn it back into a case with Status::from("shipped") when you load.

If no case matches, from() throws a . For input you do not trust, tryFrom() returns null instead, and a type written ?Status means a Status or null. Enums can hold methods too, where $this is the current case.

<?php
enum Status: string {
    case Pending = "pending";
    case Shipped = "shipped";

    public function label(): string {
        return "Order is $this->value";
    }
}
$saved = Status::Shipped->value;
echo "Saved as: $saved\n";
$loaded = Status::from($saved);
echo $loaded->label() . "\n";
$unknown = Status::tryFrom("lost");
echo gettype($unknown) . "\n";

->name is the case's name in your code, and ->value is what you store.