Advertisement
Advanced PHP, Constants & Superglobals

How do enums, introduced in PHP 8.1, provide a more type safe alternative to using class constants for representing a fixed set of related values?

Short answer

Enums let you define a fixed, named set of possible values as a distinct type, providing genuine type safety since a function parameter typed to accept a specific enum can only ever receive one of that enum's defined cases, unlike class constants which are typically just plain…

Save PHP mock interview
Advertisement
AModel answer
Enums let you define a fixed, named set of possible values as a distinct type, providing genuine type safety since a function parameter typed to accept a specific enum can only ever receive one of that enum's defined cases, unlike class constants which are typically just plain strings or integers that could accidentally be replaced with an invalid, unintended value without PHP raising any error at all.
enum OrderStatus {
    case Pending;
    case Shipped;
    case Delivered;
}

function updateStatus(OrderStatus $status) {
    echo $status->name;
}
updateStatus(OrderStatus::Shipped);
Real-world example
An order processing system replaces its previous string based status constants with a proper enum, immediately catching a bug at development time where a typo in a status string would previously have silently passed through undetected.
Likely follow-ups
  • What is the difference between a pure enum and a backed enum in PHP?
  • Can an enum implement an interface or have its own methods?
Related topics