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:
PHP
<?php class GFG { /** * @var int|float $CodingScore */ private $CodingScore ; /** * @param int|float $CodingScore */ public function setScore( $CodingScore ) { $this ->CodingScore = $CodingScore ; } /** * @return int|float */ public function getScore() { return $this ->CodingScore; } } $a = new GFG(); $a ->setScore(120.5); echo $a ->getScore(), "\r\n" ; $b = new GFG(); $b ->setScore(100); echo $b ->getScore(); ?> |
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:
PHP
<?php class GFG { private int|float $CodingScore ; // Union type public function setScore(int|float $CodingScore ): void { $this ->CodingScore = $CodingScore ; } //Union type public function getScore(): int|float { return $this ->CodingScore; } } $a = new GFG(); $a ->setScore(120.8); echo $a ->getScore(), "\r\n" ; $a ->setScore(100); echo $a ->getScore(); ?> |
Output:
120.8 100