PHP 7: Multiple function return types

Viewed 9122

So, now we got new PHP7 and we can check if return type is what we want.

For example,

function foo(): bool
{
    $num = 8;
    if (10 === $num) {
        return true;
    } else {
        return false;
    }
}
foo();

OUTPUT: false

Okey, that was easy? It works like it should, but if return is not what we expect?

function bar(): bool
{
    $num = 10;
    if (10 === $num) {
        return array(['apple', 'banana', 'strawberry']);
    } else {
        return false;
    }
}
bar();

OUTPUT: Uncaught TypeError: Return value of foo() must be of the type boolean, array returned

That was very basic and those examples just show how it works.

If we have function like in code example 2, can we check for multiple return types? Like

function bar(): bool || array    <---
{
    $num = 10;
    if (10 === $num) {
        return array(['apple', 'banana', 'strawberry']);
    } else {
        return false;
    }
}
bar();

But however this results: FATAL ERROR syntax error, unexpected '||' (T_BOOLEAN_OR), expecting '{' on line number 2

So is it possible to define multiple return types?

4 Answers

Updating this as of 2020.

There has been vote for Union types and it was accepted to PHP 8. https://wiki.php.net/rfc/union_types_v2

To have multiple return types in PHP you just need to have PHP 8, otherwise it is simply not possible at all. However, you should not be dumm and set everything as possible return, as it might make your code a mess. @Adam Cameron explains this very well in his answer.

Union types should exist, but they don't.

You can use ?int for example, but then it will expect NULL or INT.

The Answer:

It's not possible. There isn't any way natively through PHP.

However, you can omit the 'Type Declaration' which is ONLY there for strict typing. Just use DocBlocks @return bool|string for example. The IDE will recognize it, but PHP won't care.

http://docs.phpdoc.org/references/phpdoc/tags/return.html

Related