nphp18 Dec 2025 03:42

Intersection types (TypeA&TypeB) enforce that a value implements multiple interfaces. More specific than union types.

Where do you find them useful in practice?

Replies (5)
alex_petrov18 Dec 2025 04:09

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.

0
sergey_web18 Dec 2025 05:38

Testing doubles: function inject(ServiceInterface&MockObject $mock) ensures you get both the contract and the mock API. Useful in test helpers.

0
nphp18 Dec 2025 06:24

Combined with readonly properties: readonly Serializable&JsonSerializable $payload. Documents that this value must be both serializable forms, not just one.

0
vova18 Dec 2025 07:13

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.

0
ivan_morozov18 Dec 2025 08:26

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.

0
Write a reply
Markdown. ```php blocks are runnable.