What Is the "|" Character Used for in a PHP Type?

In PHP 8+, when the pipe/vertical bar symbol (i.e. "|") is used in a type, it creates a "union type", which allows multiple types to be accepted during type checking.

For example, to create a union type of int and float values, you could do the following:

// PHP 8+
function foo(int|float $num)
    // ...

This would allow passing both, int and float values, to the function "foo". Similarly, you can use union types in all positions where types are accepted (such as class properties, function/method return, etc.).

Hope you found this post useful. It was published . Please show your love and support by sharing this post.