What Are Pure Enums 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'

This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.