PHP Tutorial · Object-Oriented PHP · Lesson 34 of 38

PHP Enums

Model a fixed set of values with pure and backed enums (PHP 8.1).

Pure enums

An enum defines a type with a fixed set of possible values. Instead of passing strings like "pending" around (and mistyping them), you pass Status::Pending:

Example 1Try it yourself
<?php
enum Suit
{
    case Hearts;
    case Spades;

    public function color(): string
    {
        return match ($this) {
            Suit::Hearts => "Red",
            Suit::Spades => "Black",
        };
    }
}

$card = Suit::Hearts;
echo $card->name, " are ", $card->color(), "\n";
var_dump($card === Suit::Hearts);
echo count(Suit::cases()), " suits\n";

Output

Hearts are Red
bool(true)
2 suits

Backed enums

Backed enums have a scalar value — handy for storing in a database or JSON. from() converts a value back (throws if invalid); tryFrom() returns null instead:

Example 2Try it yourself
<?php
enum OrderStatus: string
{
    case Pending = "pending";
    case Paid = "paid";
    case Shipped = "shipped";

    public function label(): string
    {
        return ucfirst($this->value);
    }
}

$fromDb = "paid";
$status = OrderStatus::from($fromDb);
echo $status->label(), " (", $status->value, ")\n";
var_dump(OrderStatus::tryFrom("lost"));
echo json_encode(["status" => OrderStatus::Shipped]), "\n";

Output

Paid (paid)
NULL
{"status":"shipped"}

Enums can have methods and constants and implement interfaces. Practise with the enum state machine problem.

Test yourself

Which method converts a value to a backed enum case and returns null if it's invalid?

  1. from()
  2. tryFrom()
  3. cases()
  4. valueOf()
Show answer

Answer: tryFrom()

Practice next