What Are Backed Enums in PHP?

Find out what "Backed Enum" means in PHP

When you assign a scalar value to an enum case in PHP, it is called a Backed Case (because the case is "backed" by a simpler value), and an enum that contains all backed cases is called a "Backed Enum".

When using backed enums, you must adhere to the following rules:

  1. All cases can only be of a single type at a time;
  2. Cases do not have auto-generated scalar equivalents (such as a sequence of numbers), therefore, all cases must have a unique scalar value defined explicitly.

Consider, for example, the following where enum cases are assigned string values:

// PHP 8.1+
enum MyEnum: string
{
    case Foo = 'foo';
    case Bar = 'bar';
    case Baz = 'baz';
}

Backed enums are the opposite of Pure Enums (which only have cases that are singleton objects without any scalar equivalents).

Backed enums have:

  • Cases that have a read-only name property that returns the case-sensitive name of the respective case;
  • Cases that have a read-only value property that returns the value of the respective case;
  • A static cases() method that returns an array of all defined cases.

For example:

// PHP 8.1+
// ...

$cases = MyEnum::cases();

var_dump($cases); // [enum(MyEnum::Foo), enum(MyEnum::Bar), enum(MyEnum::Baz)]

echo $cases[0]->name; // 'Foo'
echo $cases[0]->value; // 'foo'

echo MyEnum::Foo->name; // 'Foo'
echo MyEnum::Foo->value; // 'foo'

Hope you found this post useful. It was published . Please show your love and support by sharing this post.