What Are Pure Enums in PHP?

Find out what "Pure Enum" means in PHP

When an enum case has no assigned (scalar) value in PHP, it is called a Pure Case, and an enum that contains only pure cases is called a "Pure Enum".

Consider, for example, the following pure enum (which only contains enum cases that have no assigned values):

// PHP 8.1+
enum MyEnum
    case Foo;
    case Bar;
    case Baz;

The opposite of Pure enums are Backed Enums (which only have cases that have scalar values).

Pure cases are not implicitly backed by a default value (such as 0 for instance); each case is, in fact, a singleton object.

Pure enums have:

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

$cases = MyEnum::cases();

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

echo $cases[0]->name; // 'Foo'
echo MyEnum::Foo->name; // 'Foo'

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