📡 You're offline — showing cached content
New version available!
Quick Access
Tutorials PHP for Beginners Enumerations (Enums)

Enumerations (Enums)

6 min read Quiz at the end
Enums define a fixed set of named values like Status::Active or Color::Red, introduced in PHP 8.1. Backed enums associate each case with a string or integer value. They replace magic strings with type-safe named options.

Enums (PHP 8.1)

// Pure enum
enum Status {
    case Active;
    case Inactive;
    case Banned;
}

$s = Status::Active;
echo $s->name;  // "Active"

// Backed enum (has a scalar value)
enum Color: string {
    case Red   = "red";
    case Green = "green";
    case Blue  = "blue";
}

echo Color::Red->value;         // "red"
$c = Color::from("green");      // Color::Green
$c = Color::tryFrom("purple");  // null

// Enum methods and interfaces
enum Suit: string {
    case Hearts   = "H";
    case Diamonds = "D";
    case Clubs    = "C";
    case Spades   = "S";

    public function label(): string {
        return match($this) {
            Suit::Hearts   => "♥ Hearts",
            Suit::Diamonds => "♦ Diamonds",
            Suit::Clubs    => "♣ Clubs",
            Suit::Spades   => "♠ Spades",
        };
    }
}

echo Suit::Hearts->label();  // ♥ Hearts
Topic Quiz · 5 questions

Test your understanding before moving on

1. Enums were introduced in PHP:
💡 Enums were introduced in PHP 8.1.
2. What is a backed enum?
💡 Backed enums have a scalar value: enum Color: string { case Red = "red"; }
3. How do you get the value of a backed enum case?
💡 ->value returns the scalar value of a backed enum case.
4. What is the difference between ->name and ->value?
💡 ->name returns "Red"; ->value returns "red" (the backed value).
5. Which method gets an enum case from its value?
💡 Color::from("red") returns the enum case with that value (throws on invalid).