Ternary operators and variable reassignment in PHP

送分小仙女□ 提交于 2019-11-29 13:03:45

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!