Union, intersection and DNF types

suggest change

PHP 7 type declarations allowed one type per parameter, property or return value, optionally made nullable with ?. PHP 8 added ways to combine types:

Feature Syntax Meaning Since
Union type int|string the value is an int or a string PHP 8.0
Intersection type Countable&Traversable the object implements Countable and Traversable PHP 8.1
DNF type (Countable&Traversable)|null a union whose members can be intersections PHP 8.2

This article covers how to write these types, how PHP converts values to them, the rules that forbid redundant types, how they behave when a method is overridden and how to check them at runtime. All examples were run with PHP 8.5. In error messages, paths are shortened to /app/.

For single-type declarations see Type hinting scalar types arrays and callables, Type hinting classes and interfaces and Nullable type hints. For declare(strict_types=1) see Strict typing. The special types mixed, never, static, null, false and true are only mentioned briefly here.

Union types

A union type lists two or more types separated by |. The value must match at least one of them:

<?php
declare(strict_types=1);

function formatId(int|string $id): string
{
    return is_int($id) ? sprintf('#%05d', $id) : strtoupper($id);
}

echo formatId(42), "\n";
echo formatId('ab-17'), "\n";

try {
    echo formatId(4.2), "\n";
} catch (TypeError $e) {
    echo $e->getMessage(), "\n";
}

Output:

#00042
AB-17
formatId(): Argument #1 ($id) must be of type string|int, float given, called in /app/union.php on line 13

The error message says string|int, not int|string. The order of types in a union has no meaning. PHP stores the types in its own order, and messages and reflection print that order.

Unions work everywhere a type is allowed: parameters, return types and typed properties (including promoted constructor properties):

<?php
declare(strict_types=1);

class Money
{
    public function __construct(
        public int|float $amount,
        public string $currency = 'EUR',
    ) {}
}

function parseAmount(string $s): int|float|null
{
    if (!is_numeric($s)) {
        return null;
    }
    return str_contains($s, '.') ? (float) $s : (int) $s;
}

foreach (['10', '9.99', 'ten'] as $s) {
    var_dump(parseAmount($s));
}

$m = new Money(5);
$m->amount = 7.5;
var_dump($m->amount);
try {
    $m->amount = '8';
} catch (TypeError $e) {
    echo $e->getMessage(), "\n";
}

Output:

int(10)
float(9.99)
NULL
float(7.5)
Cannot assign string to property Money::$amount of type int|float

The members of a union can be any types: scalars (int, float, string, bool), array, callable (not on properties), iterable, object, class and interface names, self/parent/static, null and false. A common pattern in older built-in functions is string|false, e.g. strpos() returns int|false. void, never and mixed can only be used alone.

A union replaces the @param int|string docblocks that older code used, and PHP checks it at runtime. See Polymorphism ("Emulating method overloading") for using a union to accept several kinds of arguments in one method.

?T vs T|null

?string is shorthand for string|null. The two are the same type, and reflection prints both as ?string:

<?php
function a(?string $s): ?string { return $s; }
function b(string|null $s): string|null { return $s; }
function c(int|string|null $v): string { return get_debug_type($v); }

var_dump(a(null), b(null));
echo c(null), ' ', c(1), ' ', c('x'), "\n";

echo (new ReflectionFunction('a'))->getParameters()[0]->getType(), "\n";
echo (new ReflectionFunction('b'))->getParameters()[0]->getType(), "\n";
echo (new ReflectionFunction('c'))->getParameters()[0]->getType(), "\n";

Output:

NULL
NULL
null int string
?string
?string
string|int|null

The ? can only be put in front of a single type. To make a union nullable, add null as a member:

<?php
function d(?int|string $v) {}
Parse error: syntax error, unexpected token "|", expecting variable in /app/nullable.php on line 2

Write int|string|null instead. Use ?T for a single type and T1|T2|null for unions; both forms are common style.

A default value of null used to make a parameter nullable on its own (int|string $v = null). PHP 8.4 deprecated this:

Deprecated: f(): Implicitly marking parameter $v as nullable is deprecated, the explicit nullable type must be used instead in /app/implicit.php on line 2

Fix it by writing the null explicitly: int|string|null $v = null.

Coercion of union types in coercive mode

Without declare(strict_types=1), PHP converts scalar values to the declared type when it can ('5' becomes 5 for an int parameter). With a union there may be several possible targets, so PHP follows these rules:

  1. If the value's type is part of the union, it is used as is.
  2. Otherwise PHP tries the scalar types in this order: int, float, string, bool. It picks the first one that is in the union and that the value can be converted to:
    • int: if the value is a float in the int range, an integer numeric string, or a bool
    • float: if the value is an int or any numeric string
    • string: if the value is an int or float (or a Stringable object)
    • bool: if the value is an int, float or string
<?php
// no declare(strict_types=1): coercive mode

function intOrString(int|string $v) { var_dump($v); }
function intOrFloat(int|float $v) { var_dump($v); }
function floatOrBool(float|bool $v) { var_dump($v); }
function intOrBool(int|bool $v) { var_dump($v); }

intOrString(45);       // exact type
intOrString('45');     // exact type, stays a string
intOrString(4.0);      // float with integral value
intOrString(1e20);     // float too big for int
intOrString(true);     // bool
intOrFloat('45');      // integer numeric string
intOrFloat('4.5');     // float numeric string
intOrFloat('1e3');     // float numeric string
floatOrBool(7);        // int, but only float or bool allowed
intOrBool('abc');      // non-numeric string
intOrString(4.5);      // float with a fraction

Output:

int(45)
string(2) "45"
int(4)
string(7) "1.0E+20"
int(1)
int(45)
float(4.5)
float(1000)
float(7)
bool(true)

Deprecated: Implicit conversion from float 4.5 to int loses precision in /app/coerce.php on line 4
int(4)

Things to notice:

These rules are easy to get wrong, which is a good reason to use declare(strict_types=1). In strict mode the only conversion is int to float, and only when the union contains float but not int:

<?php
declare(strict_types=1);

function floatOrString(float|string $v) { var_dump($v); }
function intOrFloat(int|float $v) { var_dump($v); }

floatOrString(7);      // int is widened to float, even in strict mode
intOrFloat(7);         // int is an exact match
try {
    intOrFloat('7');
} catch (TypeError $e) {
    echo get_class($e), ': ', $e->getMessage(), "\n";
}

Output:

float(7)
int(7)
TypeError: intOrFloat(): Argument #1 ($v) must be of type int|float, string given

Redundant types are compile-time errors

PHP rejects unions that contain the same type twice, or a type already covered by another member. The check happens when the file is compiled, so the script doesn't run at all:

<?php
function f(int|INT $v) {}
Fatal error: Duplicate type int is redundant in /app/redundant.php on line 2

Other declarations that fail the same way:

Declaration Error
int|null|null Duplicate type null is redundant
bool|false Duplicate type false is redundant (bool already includes false)
iterable|array Duplicate type array is redundant (iterable is Traversable|array)
object|Foo Type Foo|object contains both object and a class type, which is redundant
mixed|int Type mixed can only be used as a standalone type
?mixed Type mixed cannot be marked as nullable since mixed already includes null
void|int Void can only be used as a standalone type

The check only looks at the type names, without loading classes. These compile fine, even though they are redundant:

Intersection types

An intersection type, written with &, requires a value to be an instance of all the listed classes or interfaces. It's useful when a function needs the abilities of two interfaces that are not combined in one interface:

<?php
declare(strict_types=1);

function summarize(Countable&Traversable $items): string
{
    $parts = [];
    foreach ($items as $key => $value) {
        $parts[] = "$key=$value";
    }
    return count($items) . ' items: ' . implode(', ', $parts);
}

echo summarize(new ArrayObject(['a' => 1, 'b' => 2])), "\n";
echo summarize(new ArrayIterator([10, 20, 30])), "\n";

try {
    echo summarize(new EmptyIterator()), "\n";
} catch (TypeError $e) {
    echo $e->getMessage(), "\n";
}
try {
    echo summarize([1, 2]), "\n";
} catch (TypeError $e) {
    echo $e->getMessage(), "\n";
}

Output:

2 items: a=1, b=2
3 items: 0=10, 1=20, 2=30
summarize(): Argument #1 ($items) must be of type Countable&Traversable, EmptyIterator given, called in /app/intersection.php on line 17
summarize(): Argument #1 ($items) must be of type Countable&Traversable, array given, called in /app/intersection.php on line 22

EmptyIterator is Traversable but not Countable, so it's rejected. Arrays are countable and iterable, but they are not objects, so they're rejected too.

The same works with your own interfaces. Here a cache accepts any entity that has an id and can be serialized to JSON:

<?php
declare(strict_types=1);

interface HasId
{
    public function id(): int;
}

final class User implements HasId, JsonSerializable
{
    public function __construct(private int $id, private string $name) {}
    public function id(): int { return $this->id; }
    public function jsonSerialize(): array
    {
        return ['id' => $this->id, 'name' => $this->name];
    }
}

final class Cache
{
    /** @var array<int, string> */
    private array $store = [];

    public function put(HasId&JsonSerializable $entity): void
    {
        $this->store[$entity->id()] = json_encode($entity);
    }

    public function dump(): void
    {
        print_r($this->store);
    }
}

$cache = new Cache();
$cache->put(new User(7, 'Ana'));
$cache->put(new User(9, 'Ben'));
$cache->dump();

Output:

Array
(
    [7] => {"id":7,"name":"Ana"}
    [9] => {"id":9,"name":"Ben"}
)

Another common use is in tests: PHPUnit's createMock(Mailer::class) returns Mailer&MockObject, so a test property declared with that type can be passed to code expecting Mailer and also configured with ->method(...). See Mocks and test doubles.

Rules for intersections:

DNF types

PHP 8.2 allows unions whose members are intersections. The intersections must be in parentheses. This is called Disjunctive Normal Form (DNF): an OR of ANDs. The most common case is a nullable intersection:

<?php
declare(strict_types=1);

function describe((Countable&Traversable)|array|null $items): string
{
    return match (true) {
        $items === null => 'nothing',
        is_array($items) => 'array of ' . count($items),
        default => get_class($items) . ' of ' . count($items),
    };
}

echo describe(null), "\n";
echo describe([1, 2, 3]), "\n";
echo describe(new ArrayObject([1, 2])), "\n";

class Report
{
    public function __construct(
        private (Countable&Traversable)|null $rows = null,
    ) {}

    public function rowCount(): int
    {
        return $this->rows?->count() ?? 0;
    }
}

echo (new Report())->rowCount(), "\n";
echo (new Report(new ArrayIterator(['x', 'y'])))->rowCount(), "\n";

Output:

nothing
array of 3
ArrayObject of 2
0
2

DNF rules:

Declaration Error
(Foo&Bar)|Foo Type Foo&Bar is redundant as it is more restrictive than type Foo
(Foo&Bar)|(Bar&Foo) Type Bar&Foo is redundant with type Foo&Bar
(Foo&Bar)|object Type (Foo&Bar)|object contains both object and a class type, which is redundant

Variance with union and intersection types

When a method is overridden or an interface is implemented, return types may become narrower (covariance) and parameter types may become wider (contravariance). See Overriding for the general rules. With unions and intersections this means:

<?php
declare(strict_types=1);

interface Loader
{
    public function load(string $key): string|int|null;
    public function store(string $key, string $value): void;
}

class StringLoader implements Loader
{
    private array $data = [];

    // return type narrowed: string|null is a subset of string|int|null
    public function load(string $key): ?string
    {
        return $this->data[$key] ?? null;
    }

    // parameter type widened: also accepts int and Stringable
    public function store(string $key, string|int|Stringable $value): void
    {
        $this->data[$key] = (string) $value;
    }
}

$l = new StringLoader();
$l->store('a', 42);
var_dump($l->load('a'), $l->load('b'));

Output:

string(2) "42"
NULL

An intersection is narrower than any of its members, so it's a valid return type for an override that returned one of them:

<?php
interface Source
{
    public function items(): Traversable;
}

class ListSource implements Source
{
    // narrowed: an intersection is more specific than one of its members
    public function items(): Countable&Traversable
    {
        return new ArrayIterator([1, 2, 3]);
    }
}

echo count((new ListSource())->items()), "\n";

Output:

3

Going the other way is a fatal error when the class is declared. Widening a return type:

<?php
interface Loader
{
    public function load(string $key): ?string;
}

class BadLoader implements Loader
{
    public function load(string $key): string|int|null
    {
        return 1;
    }
}
Fatal error: Declaration of BadLoader::load(string $key): string|int|null must be compatible with Loader::load(string $key): ?string in /app/bad_loader.php on line 9

Narrowing a parameter type:

<?php
interface Writer
{
    public function write(int|string $v): void;
}

class BadWriter implements Writer
{
    public function write(int $v): void {}
}
Fatal error: Declaration of BadWriter::write(int $v): void must be compatible with Writer::write(string|int $v): void in /app/bad_writer.php on line 9

Property types are invariant: a child class must declare the same type. The order of union members doesn't matter (string|int may redeclare int|string), but int can't redeclare int|string:

Fatal error: Type of C::$id must be string|int (as in class A) in /app/props.php on line 4

Checking types at runtime

Inside a function that accepts a union, you usually need to branch on the actual type. Use is_int(), is_string(), is_array() etc. for built-in types and instanceof for classes. match (true) keeps it compact. get_debug_type() (PHP 8.0) returns the type name in the same form as type declarations, which makes it good for error messages and logs:

<?php
declare(strict_types=1);

final class Point { public function __construct(public int $x = 0, public int $y = 0) {} }

function handle(int|float|string|array|Point|Closure|null $v): string
{
    return match (true) {
        is_int($v), is_float($v) => "number: $v",
        is_string($v) => "string: '$v'",
        is_array($v) => 'array with ' . count($v) . ' elements',
        $v instanceof Point => "point ($v->x, $v->y)",
        $v instanceof Closure => 'closure returning ' . $v(),
        $v === null => 'null',
    };
}

foreach ([3, 2.5, 'hi', [1, 2], new Point(1, 2), fn() => 'ok', null] as $v) {
    printf("%-10s %s\n", get_debug_type($v), handle($v));
}

echo get_debug_type(new class {}), "\n";
echo get_debug_type(fopen('php://memory', 'r')), "\n";
echo gettype(1.5), ' vs ', get_debug_type(1.5), "\n";

Output:

int        number: 3
float      number: 2.5
string     string: 'hi'
array      array with 2 elements
Point      point (1, 2)
Closure    closure returning ok
null       null
class@anonymous
resource (stream)
double vs float

Prefer get_debug_type() over gettype(): gettype() returns legacy names like double, integer and boolean, and just object for every object.

If no match arm matches, PHP throws UnhandledMatchError. Since the parameter type already limits the possible values, this only happens if the union is widened and the match isn't updated, which makes the bug easy to spot.

To check an intersection at runtime, combine instanceof tests: $v instanceof Countable && $v instanceof Traversable.

Inspecting types with reflection

Reflection represents a declared type with one of three classes:

For a DNF type, ReflectionUnionType::getTypes() returns ReflectionIntersectionType objects for the parenthesized parts:

<?php
function f(
    int $a,
    ?string $b,
    int|string|null $c,
    Countable&Traversable $d,
    (Countable&Traversable)|array|null $e,
) {}

function describeType(?ReflectionType $t): string
{
    return match (true) {
        $t === null => 'none',
        $t instanceof ReflectionNamedType =>
            'named ' . $t->getName() . ($t->allowsNull() ? ' (nullable)' : ''),
        $t instanceof ReflectionUnionType =>
            'union of [' . implode(', ', array_map(describeType(...), $t->getTypes())) . ']',
        $t instanceof ReflectionIntersectionType =>
            'intersection of [' . implode(', ', array_map(describeType(...), $t->getTypes())) . ']',
    };
}

foreach ((new ReflectionFunction('f'))->getParameters() as $p) {
    printf("$%s: %s\n   %s\n", $p->getName(), $p->getType(), describeType($p->getType()));
}

Output:

$a: int
   named int
$b: ?string
   named string (nullable)
$c: string|int|null
   union of [named string, named int, named null (nullable)]
$d: Countable&Traversable
   intersection of [named Countable, named Traversable]
$e: (Countable&Traversable)|array|null
   union of [intersection of [named Countable, named Traversable], named array, named null (nullable)]

Code that reads types, such as DI containers, serializers and routers, must handle all three classes. Older code that calls $type->getName() without checking breaks on union types, because ReflectionUnionType has no getName() method. See Reflection.

When to use which

Summary

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents