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.
This article is shared by www.itechscripts.com | A leading resource of inspired clone scripts. It offers hundreds of popular scripts that are used by thousands of small and medium enterprises.