Examples of using union types in PHP 8

Home / Blog / Examples of using union types in PHP 8


In PHP 8, union types allow you to declare that a function parameter, return value, or property can accept or return multiple types, separated by the vertical bar (`|`). This feature improves code flexibility and type safety.

Example: Using Union Types in PHP 8

class Number {
    private int|float $value;

    public function setValue(int|float $value): void {
        $this->value = $value;
    }

    public function getValue(): int|float {
        return $this->value;
    }
}

$number = new Number();
$number->setValue(5);      // Accepts integer
echo $number->getValue();  // Outputs: 5

$number->setValue(11.54);  // Accepts float
echo $number->getValue();  // Outputs: 11.54

In this example, the `$value` property, the `setValue` parameter, and the `getValue` return type can all be either `int` or `float`.

Union Types with Nullable Values

You can also use union types to allow `null` values:

function getAnimal(): string|null {
    // Can return a string or null
    return null;
}

This is equivalent to the old `?string` syntax, but now you can combine more than two types.

Summary Table

| Declaration        | Meaning                   |
|--------------------|--------------------------|
| `int|float`   | Accepts int or float      |
| `string|array`| Accepts string or array   |
| `int|float`   | Accepts int or float      |

Union types make your code more expressive and robust by clearly specifying all accepted types for a variable or function.


Written by X2Y.DEV
PHP Web Dev Tips

0%