
PHP运算符优先级的一个例外
<?php
if ($a = 100 && $b = 200) {
var_dump($a, $b);
}
?>
输出是什么?
这个问题, 咋一看或许觉得简单, 但其实仔细推敲并不简单,
如果说布尔与之前的部分, 是由于优先级的问题, 但是如果仅仅是优先级的问题的话, 那么结果应该是:
$a = (100 && $b) = 200
而实际上的结果, 确实高优先级的&&让步给次优先级的=, 让 $b = 200 先结合了.
究其原因, 是因为PHP并不完全遵守优先级的定义, 这个在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.