开发者

Ternary operators and variable reassignment in PHP

开发者 https://www.devze.com 2023-02-03 02:45 出处:网络
I\'ve perused the questions on ternary operators vs. if/else structures开发者_如何学编程, and while I understand that under normal circumstances there is no performance loss/gain in using ternary oper

I've perused the questions on ternary operators vs. if/else structures开发者_如何学编程, and while I understand that under normal circumstances there is no performance loss/gain in using ternary operators over if/else structures, I've not seen any mention of this situation. Language specific to PHP (but any language agnostic details are welcome) does the interpreter reassign values in situations like this:

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

Since this would evaluate to $foo = $foo; is this inefficient, or does the interpreter simply overlook/discard this evaluation?

On a side note, what about:

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


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 not 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.


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 :/


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).


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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号