Advertisement
Advanced PHP, Type Declarations & Strict Types

What are PHP 8's enums, and how do they provide a more type safe alternative to using plain class constants for representing a fixed set of related values?

Short answer

An enum, short for enumeration, lets you define a fixed, closed set of possible named values as its own distinct type, and unlike traditional class constants, which are really just plain values with no special enforced relationship to each other, a genuine enum is fully type…

Save PHP mock interview
Advertisement
AModel answer
An enum, short for enumeration, lets you define a fixed, closed set of possible named values as its own distinct type, and unlike traditional class constants, which are really just plain values with no special enforced relationship to each other, a genuine enum is fully type checked, meaning a function that declares a parameter typed as a specific enum can only ever receive one of that enum's officially defined cases, making it impossible to accidentally pass in an unrelated, invalid value that happens to share the same underlying type, such as a plain string.
enum OrderStatus: string {
    case Pending = 'pending';
    case Shipped = 'shipped';
    case Delivered = 'delivered';
}

function updateStatus(OrderStatus $status): void { /* ... */ }
Real-world example
An order processing system defines an OrderStatus enum representing its exact set of valid statuses, preventing an invalid, misspelled status string from ever being accidentally passed into functions that specifically expect a genuine OrderStatus value.
Likely follow-ups
  • What is the difference between a pure enum and a backed enum in PHP?
  • Can an enum have its own methods, similar to a regular class?
Related topics