Enums in PHP
Learn to define pure enums and backed enums (string/int) in PHP 8.1, use enum methods, implement interfaces, and apply enums in real scenarios.
Introduction to Enums (PHP 8.1+)
Enums (PHP 8.1) are a first-class type that represents a fixed set of named values. They replace the common pattern of using class constants or integers to represent a finite set of options, with full type safety.
1. The Problem Enums Solve
Replace magic strings and integer constants with type-safe names.
Pure Enums
Pure enums (unit enums) have named cases with no associated value. They are used when you only need identity — not serialisation or database storage.
1. Defining & Using a Pure Enum
enum keyword with case declarations.
2. Comparing Enum Cases
Use === for identity comparison.
3. Enums in match Expressions
match is exhaustive and pairs perfectly with enums.
Backed Enums
Backed enums associate each case with a scalar value — useful for database storage, JSON serialisation, and API responses.
1. String-Backed Enum
Each case maps to a string value.
2. Integer-Backed Enum
Each case maps to an integer.
3. Listing All Cases — ::cases()
Get an array of all enum instances.
Enum Methods & Constants
Enums can contain methods and constants — making them richer than plain value holders.
1. Instance Methods
Add logic directly to the enum.
2. Static Methods & Constants
Factory helpers, utility logic, and shared constants.
Enums Implementing Interfaces
Enums can implement interfaces, enabling polymorphism and use in type-hinted parameters that accept any implementing type.
1. Implementing an Interface
Enums support implements but cannot extend classes.
Real-World Enum Patterns
Enums shine when replacing stringly-typed values, HTTP status codes, role systems, and state machines.
1. Database Storage
Store and retrieve enum values via their scalar backing.
2. HTTP Status Code Enum
Type-safe HTTP responses.