I\'m trying to use return in a ternary operator, but receive an error:
Parse error: syntax error, unexpected T_RETURN
Here\'s the code:
It doesn't work in most languages because return
is a statement (like if
, while
, etc.), rather than an operator that can be nested in an expression. Following the same logic you wouldn't try to nest an if
statement within an expression:
// invalid because 'if' is a statement, cannot be nested, and yields no result
func(if ($a) $b; else $c;);
// valid because ?: is an operator that yields a result
func($a ? $b : $c);
It wouldn't work for break
and continue
as well.