Strange variable assignment

风格不统一 提交于 2019-12-10 14:25:40

问题


I was studying some code I found on the web recently, and came across this php syntax:

<?php $framecharset && $frame['charset'] = $framecharset; ?>

Can someone explain what is going on in this line of code? What variable(s) are being assigned what value(s), and what is the purpose of the && operator, in that location of the statement?

Thanks! Pat


回答1:


Ah, I just wrote a blog post about this idiom in javascript:

http://www.mcphersonindustries.com/

Basically it's testing to see that $framecharset exists, and then tries to assign it to $frame['charset'] if it is non-null.

The way it works is that interpreters are lazy. Both sides of an && statement need to be true to continue. When it encounters a false value followed by &&, it stops. It doesn't continue evaluating (so in this case the assignment won't occur if $framecharset is false or null).

Some people will even put the more "expensive" half of a boolean expression after the &&, so that if the first condition isn't true, then the expensive bit won't ever be processed. It's arguable how much this actually might save, but it uses the same principle.




回答2:


&& in PHP is short-circuited, which means the RHS will not be evaluated if the LHS evaluates to be false, because the result will always be false.

Your code:

$framecharset && $frame['charset'] = $framecharset;

is equivalent to :

if($framecharset) {
    $frame['charset'] = $framecharset;
}

Which assigns the value of $framecharset as value to the array key charset only if the value evaluates to be true and in PHP

All strings are true except for two: a string containing nothing at all and a string containing only the character 0



来源:https://stackoverflow.com/questions/3640786/strange-variable-assignment

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