Using return in ternary operator

前端 未结 7 883
無奈伤痛
無奈伤痛 2020-12-03 17:46

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:

7条回答
  •  失恋的感觉
    2020-12-03 17:55

    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.

提交回复
热议问题