Intersection types
PHP 8 brought us union types, which is a feature where a parameter or return type can be one of a list of types, separated by the pipe (|
) symbol. This is a hugely useful addition to the language and allows us to loosen the type strictness while being able to avoid using mixed
as the type, or omit type hinting altogether. You can read all about union types in the RFC that was accepted into PHP 8:
PHP: rfc:union_types_v2
https://wiki.php.net/rfc/union_types_v2
There is another scenario where we might want to list multiple types, and rather than allowing things to be looser, it is a scenario where we want things to be stricter.
An intersection type is one where the parameter, variable, or return must be all of the listed types. This is opposed to union types, where it can be any of the listed types. The syntax is very similar to a union type, however, the joining character is &
instead of |
. This corresponds neatly with the standard logical meaning...