Introduced in PHP 8.1, pure enums and backed enums have the following differences:
Differences in Composition
Pure Enums:
Pure enums can only contain "Pure Cases" — i.e. a case
that has no assigned value:
// PHP 8.1+ enum MyEnum { case Foo; case Bar; case Baz; }
Please note that these cases are not implicitly backed by a default value (such as 0
for instance).
Backed Enums:
Backed enums can only contain "Backed Cases" — i.e. a case
that's assigned a scalar value:
// PHP 8.1+ enum MyEnum: string { case Foo = 'foo'; case Bar = 'bar'; case Baz = 'baz'; }
Please note that these 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 (which can only be of a single type at a time).
Properties
Both, pure enums and backed enums, have a read-only name
property which returns the case-sensitive name of the case
itself:
// PHP 8.1+ // ... echo MyEnum::Foo->name; // 'Foo'
Backed enums, however, have an additional read-only value
property that returns the value of the respective case
:
// PHP 8.1+ // ... echo MyEnum::Foo->value; // '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.