Alias Types
An alias type, or type alias, is a short name for several types at once. Under the hood, alias types are union types.
PHP offers several native alias types, such as iterable, which represents array | Traversable. Alias types are not available for customisation.
The same rules apply to alias types as other types: for example, array | iterable produces a ‘Duplicate type array is redundant’ error.
<?php
// iterable is an alias for array|Traversable: both are accepted here
function sumValues(iterable $numbers): int {
$total = 0;
foreach ($numbers as $number) {
$total += $number;
}
return $total;
}
echo sumValues([1, 2, 3]); // 6: a plain array is iterable
function threeToFive(): Generator {
yield 3;
yield 4;
yield 5;
}
echo sumValues(threeToFive()); // 12: a Generator is Traversable, also iterable
// function sumValues(array|iterable $numbers): int {} // Fatal error: Duplicate type array is redundant
?>