VOOZH about

URL: https://www.geeksforgeeks.org/php/php-8-union-types/

⇱ PHP 8 Union types - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

PHP 8 Union types

Last Updated : 27 Jul, 2021

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.

Example 1:

Output:

120.5
100
 

But after this update, Union types are specified using the following syntax

T1|T2|...

It can be used in all positions where types are currently accepted as follows.

Example 2:

Output:

120.8
100
Comment
Article Tags: