Ternary operators and variable reassignment in PHP

后端 未结 4 1224
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-20 08:22

I\'ve perused the questions on ternary operators vs. if/else structures, and while I understand that under normal circumstances there is no performance los

4条回答
  •  再見小時候
    2020-12-20 09:26

    I don't know if your first example is inefficient, but it sure is pointless. I still think an if statement is clearer:

    $foo = 'bar';
    
    if (strlen($foo) > 3)
        $foo = substr($foo, 0, 3);
    

    And while the following works, it makes no sense to place null at the end because a ternary operator is meant to be used to evaluate expressions/values, but here null does nothing other than to prevent a parse error:

    !defined('SECURE') ? exit : null;
    

    More commonly, you would see this, an example of boolean short-circuiting (or exit doesn't execute if SECURE is defined, because the or conditional expression evaluates to true automatically once at least one condition is found to be true):

    defined('SECURE') or exit;
    

    The point I'm trying to make is this: don't use ternary conditional expressions just because you can.

提交回复
热议问题