PHP Enums: Backed Values, Methods, and Safe Parsing
PHP 8.1 introduced enums: objects that represent a closed set of possible values. An enum type in a function signature restricts callers to that set, so invalid values cannot enter the domain model through that parameter. Backed enums also provide tryFrom() for parsing values from HTTP query parameters, form submissions, or webhook bodies. It returns null when a value has no matching case, letting you handle the invalid input without an unhandled exception.
Before PHP 8.1, you represented domain states with string or integer constants in a class. A string or int type hint accepted any value of that type, so you needed runtime guards, validation helpers, or static analysis docblock annotations to check the allowed values. Enums give those states their own type. They have no mutable state, but they can have methods, implement interfaces, and work with match expressions.
The syntax and design are documented in the PHP manual on enumerations and the original PHP enumerations RFC.
Why String Constants Fall Short in Domain Logic
A string parameter does not tell PHP which class constants it should accept. PHP checks that the argument is a string, so both a typo and an unrelated status pass the type check:
<?php
class OrderStatusConstants
{
public const PENDING = 'pending';
public const PAID = 'paid';
public const SHIPPED = 'shipped';
public const CANCELLED = 'cancelled';
}
function processOrder(string $status): void
{
// PHP allows any string through this parameter
}
processOrder('pendng'); // Typo accepted without error
processOrder('refunded'); // Out-of-band string accepted without error
To catch 'pendng', each function receiving $status needs a defensive check. Validation helpers can reduce the repetition, and functions like PHP string contains can inspect text formats. You still have to write those assertions, and the checks run when the code executes.
With an enum parameter, PHP rejects any argument that is not a case of that enum before the function body runs.
Pure Enums Versus Backed Enums
PHP has pure enums and backed enums. Both are described in the PHP manual on enum basics.
Pure Enums: Named Singletons
A pure enum has named cases without scalar values. Each case is a singleton object:
<?php
enum NotificationChannel
{
case Email;
case Sms;
case Push;
case Webhook;
}
Pure enums automatically implement the internal UnitEnum interface. Every case exposes a single read-only property:
$case->name: The exact case identifier as written in source code (for example,"Email").
Use a pure enum for internal logic when you do not need a scalar value to store in a database or send in an API payload. Internal state machines, dispatch strategies, and event categories are common uses.

Backed Enums: Scalar Value Associations
A backed enum gives each case a unique scalar value. Declare its type after the enum name, separated by a colon, as described in the PHP manual on backed enums:
<?php
enum OrderStatus: string
{
case Pending = 'pending';
case Paid = 'paid';
case Shipped = 'shipped';
case Cancelled = 'cancelled';
}
PHP enforces strict rules on backed enums:
- Backing types can only be
stringorint. Floats, booleans, arrays, and objects are not permitted. - Every case must define a backing value. You cannot leave some cases unbacked.
- Backing values must be unique. Two cases cannot share the same scalar literal.
- Backed enums automatically implement the internal
BackedEnuminterface, which extendsUnitEnum.
Backed enum cases expose two read-only properties:
$case->name: The case identifier as a string (such as"Pending").$case->value: The associated scalar value (such as'pending').
Use a backed enum when values need to cross a storage or API boundary. Its scalar values can go into database columns, URL query strings, or payloads exchanged with third-party web services.
Safe Parsing: from() Versus tryFrom()
Backed enums have two built-in static methods for converting scalar values into cases: from() and tryFrom(). Choose between them based on how you want to handle an unknown value.
The from() Method: Strict Assertions
The from() method returns the case matching the scalar value. If no case matches, it throws a ValueError:
<?php
// Returns OrderStatus::Paid
$status = OrderStatus::from('paid');
// Throws ValueError: "unapproved" is not a valid backing value for enum OrderStatus
$invalid = OrderStatus::from('unapproved');
Use from() for trusted internal data, such as a database column protected by foreign key or check constraints. An unknown value there points to corrupt application state or an incomplete migration. Throwing an exception makes sense when that value should never have reached storage.
The tryFrom() Method: Safe Boundary Parsing
You cannot make the same assumption about HTTP requests, query parameters, webhooks, or third-party APIs. If you call from() on an unknown user-supplied value, you need a try/catch block to handle the ValueError; otherwise, the request can end in an HTTP 500 response.
Use tryFrom() when an unknown value is an expected input error. It returns the matching case, or null if there is no match:
<?php
$rawInput = $_GET['status'] ?? null;
// Query parameters can be arrays, which tryFrom() cannot accept.
$status = is_string($rawInput) ? OrderStatus::tryFrom($rawInput) : null;
if ($status === null) {
http_response_code(422);
echo json_encode([
'error' => 'Invalid status supplied.',
'valid_options' => array_column(OrderStatus::cases(), 'value'),
]);
exit;
}
// Proceed with verified type safety
echo $status->value;
You can also combine tryFrom() with PHP's null-coalescing operator (??) to apply a fallback value when input is optional:
<?php
$rawFilter = $_GET['filter'] ?? null;
$requestedFilter = is_string($rawFilter)
? (OrderStatus::tryFrom($rawFilter) ?? OrderStatus::Pending)
: OrderStatus::Pending;
The fallback gives the rest of the code a valid enum instance even when the optional input does not match a case.
Adding Methods and Implementing Interfaces
Enums support public, protected, and private methods, including static methods. They can implement interfaces too. The rules are documented in the PHP manual on enum methods.
Inside an instance method, $this is the case you called the method on:
<?php
interface PresentableStatus
{
public function label(): string;
public function badgeClass(): string;
}
enum OrderStatus: string implements PresentableStatus
{
case Pending = 'pending';
case Paid = 'paid';
case Shipped = 'shipped';
case Cancelled = 'cancelled';
public function label(): string
{
return match ($this) {
self::Pending => 'Awaiting Payment',
self::Paid => 'Payment Confirmed',
self::Shipped => 'Order Dispatched',
self::Cancelled => 'Order Cancelled',
};
}
public function badgeClass(): string
{
return match ($this) {
self::Pending => 'badge-warning',
self::Paid => 'badge-info',
self::Shipped => 'badge-success',
self::Cancelled => 'badge-danger',
};
}
public function isFinal(): bool
{
return $this === self::Shipped || $this === self::Cancelled;
}
public function canTransitionTo(self $target): bool
{
return match ($this) {
self::Pending => in_array($target, [self::Paid, self::Cancelled], true),
self::Paid => in_array($target, [self::Shipped, self::Cancelled], true),
self::Shipped, self::Cancelled => false,
};
}
}
The enum now owns its display labels, transition rules, and classification logic. Views and services can call these methods on a case without keeping separate helper functions for the same status values.
Exhaustive Pattern Matching with match Expressions
PHP 8 introduced match, which lets you write a branch for each enum case. The syntax is covered in the PHP manual on match.
Unlike switch, which uses loose equality (==) and requires break statements, match uses strict identity checks (===) and evaluates to a value:
<?php
function getDispatchQueue(OrderStatus $status): string
{
return match ($status) {
OrderStatus::Pending => 'billing-queue',
OrderStatus::Paid => 'warehouse-queue',
OrderStatus::Shipped => 'tracking-queue',
OrderStatus::Cancelled => 'cancellation-queue',
};
}
Omitting the default arm means an unhandled case produces an error at runtime. If you later add Refunded to OrderStatus, a match expression without that case throws an UnhandledMatchError when it receives the new case.
Static analysis can catch the missing branch before that code runs. As covered in PHPStan on legacy code, PHPStan can inspect code during an automated build and flag unhandled enum cases before deployment. Add a default arm only when every remaining case should receive the same handling. Otherwise, it hides the missing branches that you want the check to report.
Immutable State Constraints and Runtime Mechanics
Enums look like classes, but the Zend Engine restricts what they can contain and how you can use them. These rules keep each case a unique, immutable singleton:
- Enums cannot declare instance properties. Adding
public string $note;inside an enum triggers a compile-time fatal error. - You cannot instantiate an enum with the
newoperator. Callingnew OrderStatus()results in a fatal error. - Enums cannot extend classes, and classes cannot extend enums. An enum is implicitly
final. - Enums cannot be cloned. Running
clone $statusthrows anErrorstating that enums are uncloneable. - Enums cannot implement magic methods such as
__construct(),__destruct(),__set(), or__get(). - Every occurrence of an enum case references the exact same object instance in memory. You can safely compare cases using the identity operator:
$status === OrderStatus::Paid.
Because cases cannot hold mutable state, they cannot leak changes to that state across request cycles. In domain models, you can use enums alongside PHP property hooks to expose typed attributes and enforce the model's rules. Later releases also expand PHP's type guarantees; the PHP 8.5 features overview covers those additions.
Step-by-Step Refactoring: From String Constants to Backed Enums
You can migrate from string constants to backed enums in stages while keeping the existing persistence layer.

Step 1: Replace Class Constants with an Enum
Start by declaring a backed enum that mirrors the existing string values used in database columns:
<?php
namespace App\Domain\Billing;
enum InvoiceStatus: string
{
case Draft = 'draft';
case Issued = 'issued';
case Paid = 'paid';
case Void = 'void';
}
Step 2: Update the Domain Model
Update the entity constructor and property types from primitive string to InvoiceStatus:
<?php
namespace App\Domain\Billing;
use DateTimeImmutable;
use DomainException;
class Invoice
{
public function __construct(
public readonly string $id,
private InvoiceStatus $status,
public readonly int $amountInCents,
public readonly DateTimeImmutable $createdAt
) {}
public function status(): InvoiceStatus
{
return $this->status;
}
public function changeStatus(InvoiceStatus $target): void
{
$allowed = match ($this->status) {
InvoiceStatus::Draft => [InvoiceStatus::Issued, InvoiceStatus::Void],
InvoiceStatus::Issued => [InvoiceStatus::Paid, InvoiceStatus::Void],
InvoiceStatus::Paid, InvoiceStatus::Void => [],
};
if (!in_array($target, $allowed, true)) {
throw new DomainException('Invalid invoice status transition.');
}
$this->status = $target;
}
}
The constructor no longer needs to check the status string against a list of allowed values. Its InvoiceStatus type tells PHP to reject anything that is not an instance of that enum.
Step 3: Parse External Input at Controller Boundaries
When an HTTP request updates an invoice, decode the JSON body, check its shape, then parse the status with tryFrom(). The entity applies its own transition rule after parsing:
<?php
namespace App\Http;
use App\Domain\Billing\Invoice;
use App\Domain\Billing\InvoiceStatus;
use DomainException;
function updateInvoiceStatus(string $json, Invoice $invoice): array
{
$payload = json_decode($json, true);
$rawStatus = is_array($payload) ? ($payload['status'] ?? null) : null;
if (!is_string($rawStatus)) {
return [400, ['error' => 'A string status field is required.']];
}
$newStatus = InvoiceStatus::tryFrom($rawStatus);
if ($newStatus === null) {
return [422, [
'error' => 'Invalid invoice status.',
'allowed' => array_column(InvoiceStatus::cases(), 'value'),
]];
}
try {
$invoice->changeStatus($newStatus);
} catch (DomainException) {
return [409, ['error' => 'Invalid invoice status transition.']];
}
return [200, [
'id' => $invoice->id,
'status' => $invoice->status()->value,
]];
}
The caller can turn the returned status code and body into an HTTP response. An unknown status gets 422; a known status that violates the invoice's transition rule gets 409.
Common Mistakes to Avoid
Watch for these mistakes when moving code to enums:

- Calling
InvoiceStatus::from($_POST['status'])directly in a controller triggers an uncaughtValueErroron bad inputs, causing unexpected 500 error pages. Always usetryFrom()at application boundaries. - Trying to store temporary state such as
$status->customNote = 'Urgent'fails because enums do not allow instance properties. State belongs on domain entities, not on the enum cases. - Comparing enums with
$status == 'paid'compares an object to a string. Compare enums with strict identity:$status === InvoiceStatus::Paidor compare scalar values with$status->value === 'paid'. - Placing a
default => nullarm on an enummatchblock silences static analysis. When a teammate adds a new case next month, the missing branch fails silently instead of alerting the developer during build verification. - PHP array keys must be integers or strings. Passing an enum object as an array key, such as
$totals[$status] = 10;, triggers aTypeError: Illegal offset type. Use the backing value instead:$totals[$status->value] = 10;.
Frequently Asked Questions
What is the minimum PHP version required to use enums?
PHP enums require PHP 8.1 or higher. Earlier PHP versions do not support the enum keyword and produce a parse error.
Can an enum implement an interface?
Yes. An enum can implement an interface as long as it does not require mutable properties or forbidden magic methods. Code that accepts the interface can then work with the enum through that contract.
How do I retrieve all cases of an enum?
Both pure and backed enums provide a static cases() method. Calling OrderStatus::cases() returns an array containing all declared case objects in declaration order. For backed enums, you can extract all raw backing values using array_column(OrderStatus::cases(), 'value').
Do backed enums serialize automatically with json_encode()?
Yes. In PHP 8.1+, passing a backed enum case to json_encode() automatically serializes it to its underlying scalar value (string or integer). Pure enums cannot be serialized by json_encode() unless they implement the JsonSerializable interface.
Can an enum case be extended by another class or enum?
No. An enum is implicitly final, and it cannot extend an existing class either.