Ternary operators and variable reassignment in PHP

后端 未结 4 1221
爱一瞬间的悲伤
爱一瞬间的悲伤 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:20

    In this cases, I use the form presented by BoltClock:

    if (strlen($foo) > 3) {
        $foo = substr($foo, 0, 3);
    }
    

    PHP does not implement something more simple to work in this cases, yet :/

    0 讨论(0)
  • 2020-12-20 09:21

    The topic that using a ternary here is not optimal has already been covered above. I'm going to address your question about whether it will reassign the value:

    This depends on what you call "reassigning". PHP does not optimize, so the $foo = $foo will be evaluated. On the other hand this will not cause PHP to copy the value of $foo to a new chunk of memory. Probably PHP will just increase the refcount on $foo and then immediately decrease it (though I'm not sure about the exact implementation details of self-assignment). So, even though PHP will execute the statement, it won't affect performance (unless you choose to write $foo = $foo seven million times in your code).

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-20 09:26

    There is always short-circuiting, although as @BoltClock said, an if statement is probably more readable in my opinion, and opens the door to else if and else conditions as well.

    strlen($foo) > 3 && $foo = substr($foo, 0, 3); 
    

    The latter statement will only be executed if the former evaluates to TRUE.

    0 讨论(0)
提交回复
热议问题