PHP 8.1 Enums: Introduction and Usage
This article explains PHP 8.1’s native enum feature, covering basic enum definitions, typed properties, methods, backed enums, serialization, case listing, reflection, traits, and practical code examples to help backend developers adopt enums in their projects.
PHP 8.1 introduces native support for enums, allowing developers to define a fixed set of constant values that can be type‑checked and used like classes.
enum Status { case DRAFT; case PUBLISHED; case ARCHIVED; }
Enums can be used as typed properties, providing compile‑time safety:
class BlogPost { public function __construct(public Status $status) {} }
Instances are created by passing an enum case:
$post = new BlogPost(Status::DRAFT);
Enums may define methods, which can be combined with match for expressive logic:
enum Status { case DRAFT; case PUBLISHED; case ARCHIVED; public function color(): string { return match($this) { Status::DRAFT => 'grey', Status::PUBLISHED => 'green', Status::ARCHIVED => 'red', }; } }
Method usage:
$status = Status::ARCHIVED; $status->color(); // 'red'
Static methods are also allowed:
enum Status { // … public static function make(): Status { // … } }
Enums can implement interfaces just like regular classes:
interface HasColor { public function color(): string; } enum Status implements HasColor { case DRAFT; case PUBLISHED; case ARCHIVED; public function color(): string { /* … */ } }
Backed enums associate each case with a scalar value (string or int):
enum Status: string { case DRAFT = 'draft'; case PUBLISHED = 'published'; case ARCHIVED = 'archived'; }
Access the scalar value via the read‑only value property and recreate an enum from a value using from or tryFrom :
$value = Status::PUBLISHED->value; // 'published' $status = Status::from('published'); $maybe = Status::tryFrom('unknown'); // null
All cases can be listed with Enum::cases() :
Status::cases(); // [Status::DRAFT, Status::PUBLISHED, Status::ARCHIVED]
Enums are objects (singletons), allowing identity comparison:
$a = Status::DRAFT; $b = Status::DRAFT; $a === $b; // true
Because enum cases are objects, they cannot be used directly as array keys:
$list = [ Status::DRAFT => 'draft' // error ];
Traits can be used in enums, but enums cannot contain properties and cannot override built‑in enum methods.
Reflection support includes ReflectionEnum , ReflectionEnumUnitCase , and ReflectionEnumBackedCase , and the helper function enum_exists() checks for enum definitions.
Enums and their cases can be annotated with attributes, and the read‑only name property provides the case name for debugging.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.