假设我们有这样一个简单的代码:
// $foo and $bar aren't defined before
$foo = 5 && $bar = 15;
// var_dump()
// $foo is (bool) TRUE
// $bar is (int) 15
所以我假设它是这样工作的:
$foo = (5 && ($bar = 15))
但在我看来应该是:
$foo = ((5 && $bar) = 15) // should throw syntax error due FALSE = 15
- 评估表从左到右 [$foo 想要 5 但 && 更高]
- && 获得最高优先级 [所以 && 需要 5 和 $bar]
- 5 == 真; $bar == Undefined [所以它是 NULL == FALSE]
- = 获得正确的关联性 [等待 (5 && $bar) 的计算]
请用最简单的方式(在其他一些例子中)向像我这样的穷人解释一下。问候。
最佳答案
我认为阅读此处的手册页有助于清除很多内容。
那么这是如何评估的呢?
$foo = 5 && $bar = 15;
首先你要知道&&
的优先级高于=
。所以第一个想法是:
$foo = (5 && $bar) = 15;
但现在是您必须阅读手册直到最后的时刻:http://php.net/manual/en/language.operators.precedence.php
引自那里:
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 of foo() is put into $a.
这是什么意思?
它默默地将 15 分配给 $bar
例如
$foo = (5 && ($bar = 15));
现在您可以评估 &&
,$bar
get 赋值 15,5 && 15
为 TRUE,get 赋值给 $富
关于php - "$foo = 5 && $bar = 15"是如何评估的,为什么它不是错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28611707/