Using return in ternary operator

前端 未结 7 798
無奈伤痛
無奈伤痛 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.

    0 讨论(0)
  • 2020-12-03 17:56

    No. But you can have a ternary expression for the return statement.

    return (!$e) ? '' : array('false', $e);
    

    Note: This may not be the desired logic. I'm providing it as an example.

    0 讨论(0)
  • 2020-12-03 17:58

    Close. You'd want return condition?a:b

    0 讨论(0)
  • 2020-12-03 18:00

    No it's not possible, and it's also pretty confusing as compared to:

    if($e) {
        return array('false', $e);
    }
    
    0 讨论(0)
  • 2020-12-03 18:03

    No, that's not possible. The following, however, is possible:

    $e = $this->return_errors();
    return ( !$e ) ? '' : array( false, $e );
    

    Hope that helps.

    0 讨论(0)
  • 2020-12-03 18:12

    This is the correct syntax:

    return  !$e ? '' : array('false', $e);
    
    0 讨论(0)
提交回复
热议问题