The vote on whether to introduce Union Types in PHP 8 has recently ended. The voting results show that 61 members of the PHP development team voted in favor and 5 voted against. Therefore, according to the voting results, Union Types 2.0 will be introduced in PHP 8.
A detailed discussion of Union Types can be found on GitHub. A “union type” accepts values of multiple different types, rather than a single one. PHP already supports two special union types:
null, using the special
Traversable, using the special
Supporting union types in the language allows us to move more type information from phpdoc into function signatures, with the usual advantages this brings:
- Types are actually enforced, so mistakes can be caught early.
- Because they are enforced, type information is less likely to become outdated or miss edge-cases.
- Types are checked during inheritance, enforcing the Liskov Substitution Principle.
- Types are available through Reflection.
- The syntax is a lot less boilerplate-y than phpdoc.