Enums deep dive

An enum in PHP is a closed set of named cases, and a backed one carries a string or an integer for storage. The four sections add storage, behaviour, parsing and JSON output to the same small set.

Backed values

A backed enum stores a string or int behind each case. The scalar fits database fields and JSON values without extra mapping.

Read the scalar through the value property. Rebuild the case from a scalar with from or tryFrom.

<?php enum Role: string { case Admin = "admin"; case Guest = "guest"; } echo Role::Admin->value, PHP_EOL; echo Role::from("guest")->name, PHP_EOL;

php backed.php

admin
Guest

The value is the stored string and the name is the case as written in the code, so one call returns the database form and the other the readable one.

Methods

Enums can hold methods much like classes do. Labels and checks live next to the cases they describe.

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

<?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

The same method runs on both cases, and $this->value is the only thing that differs.

TryFrom

The from method throws when the scalar matches no case, while tryFrom returns null instead. User input and database rows deserve the soft form.

Check the result for null before moving on. That one check replaces long validation chains.

<?php enum Role: string { case Admin = "admin"; case Guest = "guest"; } $role = Role::tryFrom("admin"); if ($role === null) { echo "Unknown role", PHP_EOL; } else { echo $role->name, PHP_EOL; } var_dump(Role::tryFrom("boss")); try { Role::from("boss"); } catch (ValueError $e) { echo get_class($e), ": ", $e->getMessage(), PHP_EOL; }

php tryfrom.php

Admin
NULL
ValueError: "boss" is not a valid backing value for enum Role

The known scalar becomes the case, the unknown one becomes null from the soft call and an exception from the strict one.

JsonSerializable

A backed enum already turns into JSON through its scalar value, with no interface at all. Implementing JsonSerializable lets the enum choose a richer shape for the API, and the output stays stable and easy to read.

Return value from jsonSerialize and let json_encode handle the rest.

<?php enum Role: string { case Admin = "admin"; case Guest = "guest"; } enum Labeled: string implements JsonSerializable { case Admin = "admin"; public function jsonSerialize(): array { return ["value" => $this->value, "label" => "Administrator"]; } } echo json_encode(Role::Admin), PHP_EOL; echo json_encode(Labeled::Admin), PHP_EOL;

php json.php

"admin"
{"value":"admin","label":"Administrator"}

The plain backed case is already JSON as its value, and the class that implements the interface decides the object that replaces it.

Exercises

  1. Add a third case to Role and print its name and value.
  2. Write a method that returns true for one case and false for the others.
  3. Parse a list of strings with tryFrom() and collect the unknown ones.
  4. Make an enum serialise to an object with a value and a label.
  5. Compare json_encode() of a backed case with and without the interface.

Questions

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

  1. What does Role::Admin->value return for case Admin = "admin";?

    Answer

    admin

    value is the backing scalar, while name is the case identifier as written.

  2. What does tryFrom() return when no case matches?

    Answer

    null

    tryFrom() is the soft form and answers null, while from() throws.

  3. What does from() do with a scalar that matches no case?

    Answer

    It throws a ValueError

    The strict form refuses the value with an exception, which the caller has to catch.

  4. What does $this point at inside an enum method?

    Answer

    The current case

    A method on an enum runs on one case, and $this gives access to its value and name.

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

    Answer

    guest

    The value property holds the backing string of the case.

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

    Answer

    Guest

    from() rebuilds the case and name is the identifier Guest.

  7. What does this program print? <?php enum Role: string { case Admin = "admin"; case Guest = "guest"; } var_dump(Role::tryFrom("boss"));

    Answer

    NULL

    The soft lookup finds no case and returns null without throwing.

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

    Answer

    Role: admin

    The method reads the backing value, which is the lowercase admin.

  9. What does this program print? <?php enum Role: string { case Admin = "admin"; } echo json_encode(Role::Admin);

    Answer

    "admin"

    A backed enum is encoded as its scalar value without any interface.

  10. What can an enum that implements JsonSerializable control?

    Answer

    The shape of the JSON that replaces it

    jsonSerialize() returns what json_encode() writes, so the enum can export an object or a richer value.

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