Wed. Jul 15th, 2020

PHP 8 will ship with Union Types 2.0

1 min read

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:

  • Type or null, using the special ?Type syntax.
  • array or Traversable, using the special iterable type.

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.