🐘 PHP Advanced

What are intersection types in PHP 8.1?

Why Interviewers Ask This

Interviewers ask this to evaluate whether you have the depth of knowledge needed to mentor others and lead technical decisions. The expected answer goes beyond definitions into practical implications and real-world consequences.

Answer

Intersection types (PHP 8.1) allow declaring that a value must satisfy multiple type constraints simultaneously, using the & operator. Example: function process(Iterator&Countable $collection): void — the argument must implement both Iterator AND Countable. This is the opposite of union types (|, introduced in PHP 8.0), which accept any one of the specified types. Intersection types can only be used with class and interface names — not with primitive types like int, string, or null. They improve type safety for code that requires objects with multiple capabilities, eliminating the need to create a combined interface just to express the type constraint. Pure intersection types (A&B) cannot be mixed with union types yet (that is a future proposal).

Common Mistake

Many candidates answer correctly but can't explain the 'why'. Always be prepared to justify your answer with a concrete example or use case from your PHP experience.