PHP enums provide a clean way to represent a fixed set of possible values. When working with a backed enum, each enum case has an associated scalar value, such as a string or integer. A common situation is receiving a value from a database, API request, form, or another external source and needing to retrieve the corresponding enum case. For this purpose, PHP provides the from() method.
# Creating a Backed Enum
Consider a simple enum representing the status of an order:
enum OrderStatus: string
{
case Pending = 'pending';
case Processing = 'processing';
case Completed = 'completed';
case Cancelled = 'cancelled';
}
You can convert that value into its corresponding enum:
$status = OrderStatus::from('processing');
# now $status is : OrderStatus::Processing
This is particularly useful when you want to work with enum cases instead of raw strings:
# What Happens If the Value Does Not Exist?
The from() method expects a valid backed value. Since invalid does not belong to the enum, PHP throws a ValueError. This means from() is useful when you are certain that the value is valid.
# Using tryFrom() for Unknown Values
If the value may not be valid, use tryFrom() instead:
$status = OrderStatus::tryFrom('invalid');
# $status will be null
This makes tryFrom() a safer option when working with user input, external APIs, or any value that may not match one of your enum cases.
Do you usually use PHP enums in your projects? share experiences in the comments