Enums

An enum gives a name to each allowed value of a small set. In PHP the cases are real objects, so a type hint accepts exactly the cases of the enum and nothing else.

Define an enum

An enum lists a fixed set of allowed cases. It replaces loose strings with values the engine can check.

Type hints with the enum name reject every value outside the list.

<?php enum Status { case Draft; case Published; } echo Status::Draft->name, " ", Status::Published->name, PHP_EOL;

php enum.php

Draft Published

The name property holds the case name as written in the declaration. A string with the same letters is not a case, so a parameter typed Status refuses "Draft".

Backed enums

A backed enum stores a string or int behind each case. This form fits database fields and JSON values.

Read the scalar with the value property and rebuild with the from method.

<?php enum Role: string { case Admin = "admin"; case Guest = "guest"; } echo Role::Admin->value, PHP_EOL; echo Role::from("guest")->name, PHP_EOL; try { Role::from("owner"); } catch (ValueError $e) { echo get_class($e), PHP_EOL; }

php backed.php

admin
Guest
ValueError

The value leaves the enum as a plain string, and the from method turns a string back into the case it belongs to. A value that belongs to no case is refused with a ValueError, which is why the catch is there.

Methods on enums

Enums can hold methods like classes do. Use them to place labels and checks next to the cases.

Inside a method, $this points to the current case and gives access to its value.

<?php enum Role: string { case Admin = "admin"; case Guest = "guest"; public function label(): string { return "Role " . $this->value; } } echo Role::Admin->label(), PHP_EOL; echo Role::Guest->label(), PHP_EOL;

php methods.php

Role admin
Role guest

Each case carries the method, and $this is the case the call went to. The label stays next to the values it describes instead of in a helper array somewhere else.

Match on enums

Expression match pairs well with enums because it checks all cases in one place.

Each arm names one case and returns a value without long chains of conditions.

<?php enum Status { case Draft; case Published; } function describe(Status $s): string { return match ($s) { Status::Draft => "Not ready", Status::Published => "Live", }; } echo describe(Status::Draft), PHP_EOL; echo describe(Status::Published), PHP_EOL;

php matchenum.php

Not ready
Live

The match compares cases, not strings, and every case has its arm. A new case without an arm makes the match throw an UnhandledMatchError at run time, which is PHP's way of pointing at the missing line.

Exercises

  1. Add a third case to Status and run the first and the last program again. Which one complains first?
  2. Give Role an int-backed twin with three levels and print every value.
  3. Add a method that returns true for one case and false for the others.
  4. Store a case in a variable, print it, and compare it with a string of the same letters.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What is an enum?

    Answer

    A fixed set of named cases

    The enum declares every allowed case once, and the engine accepts only those values.

  2. What does a backed enum add to its cases?

    Answer

    A value behind every case

    The backing type is declared after the colon, and every case carries one value of that type.

  3. Which property reads the scalar of a backed case?

    Answer

    ->value

    The value property holds the string or int of the case, and name holds the case name.

  4. How do you rebuild a backed case from its value?

    Answer

    Role::from("guest")

    The from method looks the value up and returns the case; an enum is never built with new.

  5. What does this program print? <?php enum Status { case Draft; case Published; } echo Status::Draft->name;

    Answer

    Draft

    Every case has a name property that holds the case name as it was declared.

  6. What does this program print? <?php enum Role: string { case Admin = "admin"; case Guest = "guest"; } echo Role::Admin->value;

    Answer

    admin

    The value property of the Admin case is the string written after the equals sign.

  7. What does this program print? <?php enum Role: string { case Admin = "admin"; case Guest = "guest"; public function label(): string { return "Role " . $this->value; } } echo Role::Guest->label();

    Answer

    Role guest

    The call goes to the Guest case, so $this carries its value of guest.

  8. What does this program print? <?php enum Status { case Draft; case Published; } function describe(Status $s): string { return match ($s) { Status::Draft => "Not ready", Status::Published => "Live", }; } echo describe(Status::Draft), " / ", describe(Status::Published);

    Answer

    Not ready / Live

    Each call matches its own case and takes the string of that arm.

  9. What does this program print? <?php enum Role: string { case Admin = "admin"; case Guest = "guest"; } try { Role::from("owner"); } catch (ValueError $e) { echo get_class($e); }

    Answer

    ValueError

    No case backs the string owner, so from throws a ValueError.

  10. What does this program print? <?php enum Status { case Draft; case Published; } $status = Status::Draft; var_dump($status === "Draft");

    Answer

    bool(false)

    A case is an object, not its name, so a strict comparison with the string is false.

The code on this page was run with PHP 8.5.13 (php -v) in Alpine Linux, with the commands shown above.

Article author: Arthur Isaev