Back to results for “Enums”
PHP › PHP 8 Features (Attributes, Enums, Match, Nullsafe Operator)

What are enums introduced in PHP 8.1, and how do backed enums differ from pure enums in terms of the values they can represent?

Intermediate

Answer

A pure enum defines a fixed set of named cases without any underlying scalar value associated with each case, while a backed enum additionally associates each case with a specific string or integer value, letting you convert between the enum case and its underlying value, which is especially useful when the enum's values need to be stored in a database or represented in an external API, unlike a pure enum which exists purely as a type safe in memory concept.
enum OrderStatus: string {
    case Pending = 'pending';
    case Shipped = 'shipped';
}
echo OrderStatus::Pending->value;
$status = OrderStatus::from('shipped');
Real-world example An order management system uses a backed enum for order status, storing the underlying string value directly in the database while working with the fully type safe enum case throughout the rest of the application code.

Common follow-ups: What is the difference between the from and tryFrom methods on a backed enum?;Can an enum implement an interface and have its own additional methods?