Precedence operator 'OR' and '=' in PHP

坚强是说给别人听的谎言 提交于 2019-12-10 23:57:07

问题


$a = 1;
$a OR $a = 'somthing'
echo $a; //1

Why? If = have much precedence then 'OR' then why OR execute first?


回答1:


Because if OR has higher precedence then

$a OR $a = 'somthing'

will be parsed as:

($a OR $a) = 'somthing'

that would be technically wrong because you can't assign to an expression (while programmers would like to write expression like this is coding so it should be a valid expression).

because precedence of or operator was low hence the expression $a OR $a = 'somthing' pareses as $a OR ($a = 'somthing') And according to short-circuit first operand that is $a was evaluated as true and second operand expression not evaluated and a remains 1.

Remember precedence rules derives grammar rules and hence tells how expression will be parse. But precedence is a compile-time property that tells us how expressions are structured. Evaluation is a run-time behavior that tells us how expressions are computed (hence how expressions will be evaluates can't completely determine by precedence). And PHP docs seems to say same:

Operator Precedence
Operator precedence and associativity only determine how expressions are grouped, they do not specify an order of evaluation. PHP does not (in the general case) specify in which order an expression is evaluated and code that assumes a specific order of evaluation should be avoided, because the behavior can change between versions of PHP or depending on the surrounding code.




回答2:


When you put OR between two statement, if the first one returns true, the second one never will be executed.

in this case, the first statement ( $a ) returns true ( because $a = 1 ), so the

second one ( $a = 'somthing'; ) wont be executed.




回答3:


Because 1 is truthy.

What you're saying with $a OR $a = 'somthing'; is

a is true OR set it to "somthing"

. Well, a is true, so it won't be set, while the following code would do.

$a = false;
$a OR $a = 'somthing';
echo $a; //"something"


来源:https://stackoverflow.com/questions/21596754/precedence-operator-or-and-in-php

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