Skip to content
Advertisement

PHP8: vertical line with a type?

I found this line of code to be problematic on a server running PHP7.4:

public function expiresAfter(int|DateInterval|null $time);

I get a ParseError, with PHP expecting a variable. Couldn’t find the symbol’s usage as it is here in Reference — What does this symbol mean in PHP?

What do the vertical bars mean here? Also is there a way to rewrite this so it works with PHP7.4?

Advertisement

Answer

Those are union types (new in PHP8):

Union types are a collection of two or more types which indicate that either one of those can be used.

Example:

public function foo(Foo|Bar $input): int|float;

They work like an or condition on Object/Type you can use as an input parameter. In this example you can either use Foo or Bar as an input parameter, but nothing else.

If you want to get your code working on PHP7.4 just remove the types like so:

public function foo($input);

Source: https://stitcher.io/blog/new-in-php-8#union-types-rfc

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement