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?