Model immutable domain types with PHP enums and readonly
8 steps · about 2 h 5 min · Intermediate
- PHP enumerations overview (reference, PHP Manual, 15 min)
See how PHP 8.1+ enums replace ad-hoc class constants with closed, type-checked case sets.
- Basic (pure) enumerations (reference, PHP Manual, 15 min)
Define pure enum cases and compare them by identity without accidental scalar coercion.
- Backed enumerations (from and tryFrom) (reference, PHP Manual, 20 min)
Map database strings and API payloads safely onto typed enum cases with tryFrom().
- Adding methods and interfaces to PHP enums (reference, PHP Manual, 15 min)
Keep state-specific behaviour on the enum itself instead of scattering switch blocks across callers.
- Differences between enums and regular objects (reference, PHP Manual, 15 min)
Learn why enums disallow state, cloning and constructors so singleton case guarantees hold.
- Strict, exhaustive match expressions (reference, PHP Manual, 20 min)
Pair enums with match() for identity comparisons, return values and UnhandledMatchError safety.
- Controlling inheritance with final classes and methods (reference, PHP Manual, 10 min)
Lock down value-object invariants so subclasses cannot silently reintroduce mutability.
- Object cloning and immutable with-style updates (reference, PHP Manual, 15 min)
Understand __clone semantics in PHP 8.2+ readonly classes when deriving modified value-object copies.