How do union types and intersection types in PHP 8 provide more expressive and precise type declarations than were previously possible?
Short answer
Union types, introduced in PHP 8, let a parameter, property, or return type accept one of several specified types, such as accepting either an integer or a string, while intersection types, introduced in PHP 8.1, require a value to simultaneously satisfy multiple interfaces at…
Advertisement
AModel answer
Union types, introduced in PHP 8, let a parameter, property, or return type accept one of several specified types, such as accepting either an integer or a string, while intersection types, introduced in PHP 8.1, require a value to simultaneously satisfy multiple interfaces at once, both providing significantly more precise and expressive type declarations than were possible in earlier PHP versions, which previously often required falling back to the less precise generic mixed type or relying purely on docblock comments for this kind of nuanced type information.
function processId(int|string $id): void {
}
function save(Countable&Iterator $collection): void {
}Real-world example
A function accepting either a numeric database identifier or a string based slug uses a union type to precisely document both accepted possibilities, letting PHP itself enforce and validate this constraint rather than relying purely on a comment that could easily become outdated.
Likely follow-ups
- How do union types interact with strict_types mode regarding automatic type coercion?
- What are practical real world use cases specifically for intersection types?
Related topics