Intersection types in PHP 8.1: actual use cases
Intersection types (TypeA&TypeB) enforce that a value implements multiple interfaces. More specific than union types.
Where do you find them useful in practice?
Most useful when you combine interfaces that your code relies on together. function process(Traversable&Countable $collection) needs both: iteration and a count for progress reporting. Without intersection types you had to document this convention or create a combined interface.
Testing doubles: function inject(ServiceInterface&MockObject $mock) ensures you get both the contract and the mock API. Useful in test helpers.
Combined with readonly properties: readonly Serializable&JsonSerializable $payload. Documents that this value must be both serializable forms, not just one.
Intersection types do not allow primitive types (int, string). Only class and interface types. If you need a string that also validates, you still need a value object.
PHP 8.2 added DNF types (disjunctive normal form): (A&B)|null. This is the main one people wanted: a nullable intersection type. Used frequently with optional dependency injection.
```php blocks are runnable.