A backed enum in PHP is an enumeration whose cases are explicitly backed by a scalar value, specifically either anDocumentation Index
Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt
Use this file to discover all available pages before exploring further.
int or a string. Introduced in PHP 8.1, backed enums allow enumeration cases to be serialized and deserialized by associating a unique, literal scalar value with each case.
Syntax and Declaration
To create a backed enum, you must declare the scalar type immediately following the enum name. Every case within the enum must be explicitly assigned a value matching that type.Technical Constraints
- Strict Typing: The backing type must be exactly
intorstring. Union types (e.g.,int|string) are strictly prohibited. - Homogeneity: An enum cannot mix integer and string values. All cases must resolve to the declared backing type.
- Uniqueness: Every case value must be unique within the enumeration. Two cases cannot share the same scalar value.
- Literal Values: The assigned values must be literals or literal expressions. Variables, function calls, or dynamic expressions are not allowed.
Accessing the Backing Value
Backed enums expose their underlying scalar value via a read-only public property namedvalue.
Deserialization Methods
Backed enums implicitly implement theBackedEnum interface, which provides two static methods for converting a scalar value back into an enum instance.
from()
The from() method takes a scalar value and returns the corresponding enum case. If the value does not exist within the enum, it throws a ValueError.
tryFrom()
The tryFrom() method operates similarly to from(), but instead of throwing an exception on failure, it returns null. This is the preferred method when handling untrusted input.
The BackedEnum Interface
Under the hood, the PHP engine ensures that all backed enums implement the BackedEnum interface, which extends the base UnitEnum interface. The engine defines it as follows:
$value property is not declared within the BackedEnum interface itself, as PHP interfaces traditionally cannot declare properties. Instead, the PHP engine automatically exposes the $value property directly on the instantiated backed enum objects.
Because it extends UnitEnum, a backed enum also inherits the cases() method, which returns an array of all cases defined in the enumeration in their order of declaration.
Master PHP with Deep Grasping Methodology!Learn More





