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.).


This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.