[英]About logical operator && in php
here is the code 这是代码
$a = 2;
$a && $a = 1;
var_dump( $a ); // result 1
Why $a is 1? 为什么$ a是1?
According to the document, logical operator '&&' has greater precedence than assign operator, it should be interpreted as ($a && $a) = 1, then there should be a syntax error. 根据文档,逻辑运算符“ &&”比赋值运算符具有更高的优先级,应将其解释为($ a && $ a)= 1,然后应该存在语法错误。
From the documentation 从文档中
Note: 注意:
Although=
has a lower precedence than most other operators, PHP will still allow expressions similar to the following:if (!$a = foo())
, in which case the return value offoo()
is put into$a
. 尽管=
的优先级比大多数其他运算符低,但PHP仍将允许类似于以下表达式:if (!$a = foo())
,在这种情况下,foo()
的返回值放入$a
。
The documentation doesn't specify what rules are followed at this point, but we can infer that your code is equivalent to this: 该文档目前未指定要遵循的规则,但是我们可以推断出您的代码与此等效:
$a && ($a = 1)
Because &&
is "lazy" in that it won't bother evaluating further arguments if it finds one that's false, this means that $a
will only be set to 1
if it previously held a truthy value (in your case, 2
is truthy). 因为&&
是“懒惰的”,因为如果发现一个错误的值,它将不再费心评估其他参数,这意味着$a
仅在先前具有真实值的情况下才设置为1
(在您的情况下, 2
为真实值) 。 If you had set $a = 0
then it would have stayed 0
. 如果您将$a = 0
设置$a = 0
则它将保持为0
。
The way it's written, you're saying the same thing as this 它写的方式,你是在说同样的话
$a = 2;
if($a) $a = 1;
Since 2
is something , it succeeds and changes $a
to 1. 由于2
是某物 ,因此它将成功并将$a
更改为1。
So why does it do this? 那么为什么要这样做呢? You have a statement that $a = 2
; 您有一个语句$a = 2
; There's no order of operations here so PHP processes it. 这里没有操作顺序,因此PHP会对其进行处理。 The order of operations DOES come into effect on the second statement. DOES的操作顺序在第二条语句上生效。 Remember, $a
is SOMETHING, (ie truthy). 记住, $a
是$a
东西(即真实)。 Let's change your code slightly 让我们稍微更改一下代码
$a = 0;
$a && $a = 1;
echo $a;
As you can see, $a
is now falsy. 如您所见, $a
现在是虚假的。 So the order prevents the script from changing the value and the script outputs 0
因此,该顺序可防止脚本更改值,并且脚本输出0
$a && $a = 1;
is an expression of boolean type. 是布尔类型的表达式。 Since $a
is truthy, the evaluation of the expression continues onto the second part, which is the assignment. 由于$a
是真实的,因此表达式的求值继续到第二部分,即赋值。 As a side effect of the assignment, $a
now holds 1
. 作为赋值的副作用, $a
现在拥有1
。
If $a
had been 0 in the start, it'd remain 0 in the end, as the evaluation of the expression'd be terminated right after testing the first condition. 如果$a
开头为0,则结尾始终为0,因为在测试第一个条件之后立即终止表达式的求值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.