A new RFC has been finished voting and accepted for PHP - 8. That is "Union Types", which is an extension of PHP's type system.
A union type accepts values of multiple different types, rather than a single one. PHP already supports two special union types:
Type
or null
, using the special ?Type
syntax.array
or Traversable
, using the special iterable
type.However, arbitrary union types are currently not supported by the language. A Union type essentially declares an OR condition for multiple types in the argument type, return type or property type declaration.
The RFC Proposal:
Union types are specified using the syntax T1|T2|…
and can be used in all positions where types are currently accepted (Taken from the RFC example):
class Number {
private int|float $number;
public function setNumber(int|float $number): void {
$this->number = $number;
}
public function getNumber(): int|float {
return $this->number;
}
}
Union types support all types currently supported by PHP, with some caveats. This is just a glimpse, to learn more please read the PHP RFC: Union Types 2.0.