Union Types
A parameter or return value that is declared using a union type
such as bool|int
allows multiple, different types for
its values rather than just a single type. Prior to PHP 8, the
language already had limited support for union types for special
cases:
?Type
to denote that values of typeType
are allowed as well asnull
(see the “Nullable Types” section)iterable
to denote that values of typearray
andTraversable
are allowed (see the “TheIterable
Type” section)catch (FooException|BarException $e)
to denote that acatch
block can handle exceptions of typeFooException
as well asBarException
(see the “Handling Multiple Exception Types with onecatch
Statement” section
PHP 8 introduces full support for union types to all places where
types can be declared. Here is an example of a function,
f()
, that uses a union type in the declaration of its
parameter:
function f(bool|int $a): void
{
var_dump($a);
}
The function shown above declares that it accepts values of type
bool
or int
as arguments for its
$a
parameter. Below you can see how f()
behaves when scalar types are not interpreted strictly:
f(false); // Will print bool(false)
f(true); // Will print bool(true)
f(0); // Will print int(0)
f(1); // Will print int(1)
f(1.2); // Will print int(1)
f('1234'); // Will print int(1234)
f('1234abcd'); // Will print int(1234) and trigger a notice
f(''); // Will print bool(false)
f('a'); // Will print bool(true)
f(new stdClass); // Will result in a type error
Below you can see how f()
behaves when scalar types
are interpreted strictly:
f(false); // Will print bool(false)
f(true); // Will print bool(true)
f(0); // Will print int(0)
f(1); // Will print int(1)
f(1.2); // Will result in a type error
f('1234'); // Will result in a type error
f('1234abcd'); // Will result in a type error
f(''); // Will result in a type error
f('a'); // Will result in a type error
f(new stdClass); // Will result in a type error