PHP 8 Union types
A “union type” accepts values of multiple different data types, rather than a single one. If the programming language supports union types, you can declare a variable in multiple types. For example, there can be a function that can accept the variable of type “string” or “float” as a parameter. PHP already supports two special union types.
- Type or null, using the special “?Type” syntax.
- Array or Traversable, using the special iterable type.
But before the update, arbitrary union types were not supported by the language. Instead, we used PHPDoc annotations which was quite a work to do.
But after this update, Union types are specified using the following syntax
It can be used in all positions where types are currently accepted as follows.
My Personal Notes arrow_drop_up
Please Login to comment...