2 min read

Last week, the Union Types 2.0 RFC by Nikita Popov, a software developer at JetBrains got accepted for PHP 8.0 with 61 votes in favor and 5 against. Popov submitted this RFC as a GitHub pull request to check whether it would be a better medium for RFC proposals in the future, which got a positive response from many PHP developers.

What the Union Types 2.0 RFC proposes

PHP type declarations allow you to specify the type of parameters and return values acceptable by a function. Though for most of the functions, the acceptable parameters and possible return values will be of only one type, there are cases when they can be of multiple types.

Currently, PHP supports two special union types. One is the nullable types that you can specify using the ‘?Type’ syntax to mark a parameter or return value as nullable. This means, in addition to the specified type, NULL can also be passed as an argument or return value. Another one is ‘array’ or ‘Traversable’ that you can specify using the special iterable type.

The Union Types 2.0 RFC proposes to add support for arbitrary union types, which can be specified using the syntax T1|T2|… Support for Union types will enable developers to move more type information from ‘phpdoc’ into function signatures. Other advantages of arbitrary union types include early detection of mistakes and less boilerplate-y code compared to ‘phpdoc’. This will also ensure that type is checked during inheritance and are available through Reflection.

This RFC does not contain any backward-incompatible changes. However, existing ReflectionType based code will have to be adjusted in order to support the processing of code that uses union types.

The RFC for union types was first proposed 4 years ago by PHP open source contributors, Levi Morrison and Bob Weinand. This new proposal has a few updates compared to the previous one that Popov shared on the PHP mailing list thread:

  • Updated to specify interaction with new language features, like full
    variance and property types.
  • Updated for the use of the ?Type syntax rather than the Type|null syntax.
  • It only supports “false” as a pseudo-type, not “true”.
  • Slightly simplified semantics for the coercive typing mode.

In a Reddit discussion, many developers welcomed this decision. A user commented, “PHP 8 will be blazing. I can’t wait for it.” While some others felt that this a one step backward. “Feels like a step backward. IMHO, a better solution would have been to add function overloading to the language, i.e. give the ability to add many methods with the same name, but different argument types,” a user expressed.

You can read the Union Types 2.0 RFC to know more in detail. You can read the discussion about this RFC on GitHub.

Read Next

Symfony leaves PHP-FIG, the framework interoperability group

Oracle releases GraphPipe: An open-source tool that standardizes machine learning model deployment

Connecting your data to MongoDB using PyMongo and PHP