๐ŸŽ“ A1Learner
๐Ÿ”
0 of 27 lessons completed

Backed Enums

A backed enum is an enum where each case also stores a value. The stored value is a string or an integer, and it links the case to saved data.

The stored value prints

The Status enum stores text for each case. The value property of the Draft case prints the stored text.

<?php
enum Status: string {
  case Draft = "draft";
  case Published = "published";
}
echo Status::Draft->value . "\n";

from finds a case and tryFrom can miss

The from call turns the stored text draft back into the Draft case. The tryFrom call finds no case for the text nope, so the dump shows NULL.

<?php
enum Status: string {
  case Draft = "draft";
  case Published = "published";
}
$found = Status::from("draft");
echo $found->name . "\n";
$missing = Status::tryFrom("nope");
var_dump($missing);

A backed enum takes an interface

Status takes the HasLabel interface and writes its label method. A function typed by the interface prints the labels of two cases.

<?php
interface HasLabel {
  public function label();
}
enum Status: string implements HasLabel {
  case Draft = "draft";
  case Live = "live";
  public function label() {
    return match($this) {
      Status::Draft => "Not yet shared",
      Status::Live => "Shared with readers",
    };
  }
}
function showLabel(HasLabel $item) {
  echo $item->label() . "\n";
}
showLabel(Status::Draft);
showLabel(Status::Live);

Example

<?php
enum Level: int {
  case Low = 1;
  case Medium = 2;
  case High = 3;
  public function label() {
    return match($this) {
      Level::Low => "Easy pace",
      Level::Medium => "Steady pace",
      Level::High => "Hard pace",
    };
  }
}
$stored = 2;
$level = Level::from($stored);
echo $level->name . "\n";
echo $level->label() . "\n";

Key points

  • A colon and a type after the enum name set the stored type.
  • Each case gives its stored value after an equals sign.
  • The value property reads the stored value from a case.
  • The from method turns a stored value back into its case.
  • The tryFrom method returns null when no case holds the given value.
  • A backed enum can take an interface and write the methods the interface names.

In this example, the Level enum stores a whole number for each case. The stored number 2 comes back through the from method as the Medium case. The name line prints Medium, and the label method then prints its pace line.

Note

A backed case still carries the name property beside its stored value.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does tryFrom return when no case holds the given value?