PHP Union Type

Description

Allows multiple possible types[fn:rc] to be given to a parameter/member.

Syntax

class Example {
private int|float $foo;

public function __construct(int|float $foo) {
    $this->foo = $foo;
}

public function doSomethingWithMultipleTypes(float|int $bar): int|float {
    return ($bar + $this->foo) * 2;
}

}

Inheritance

class A{
public function foo(string|int $foo): string|int {}
}

class B extends A{
public function foo(string|int|float $foo): string {}
}

Footnotes

[fn:rfc]https://wiki.php.net/rfc/union\_types\_v2