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

How can PHP 8's readonly properties, enums, and first class callable syntax be combined together to build more robust, immutable, and expressive domain models compared to earlier PHP versions?

Advanced

Answer

Combining readonly properties for guaranteed immutability, backed enums for representing a fixed, type safe set of domain concepts like an order status, and first class callable syntax for cleanly referencing existing methods as callables, lets developers building domain models express business concepts with significantly stronger guarantees and less boilerplate than was achievable in earlier PHP versions, where similar intent often had to be enforced purely through convention and documentation rather than the language itself actively catching violations.
final class Order {
    public function __construct(
        public readonly string $id,
        public readonly OrderStatus $status,
    ) {}
}
$statuses = array_map(OrderStatus::from(...), $rawStatuses);
Real-world example A team modernizing a legacy PHP application redesigns its core Order domain model using readonly properties and a backed enum for status, immediately eliminating an entire category of bugs where an order's status or identifier could previously be accidentally mutated somewhere deep within the codebase.

Common follow-ups: How do these modern PHP 8 features specifically compare to similar immutability and type safety features in other programming languages?;What migration challenges arise when adopting these features in a large, existing legacy codebase?