<?php
if ($a = 100 && $b = 200) {
var_dump($a, $b);
}
// 輸出:bool(true) int(200)
// 而非預期的 int(100) int(200)
?>
雖然 `=` 優先級低於 `&&`,但 PHP 解析器有特殊規則:當 `=` 左側是變數,右側包含 `&&`/`||` 時,允許右側表達式優先結合。實際解析為:
$a = (100 && ($b = 200))
步驟:
這違背直覺的優先級預期 `(($a = 100) && $b) = 200` (語法錯誤)。
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.
這是歷史設計決策,為了支持 `if ($a = foo())` 這類賦值兼判斷慣用語。C 語言中此類代碼屬語法錯誤。
and / or / xorand / or 優先級低於 `=`,因此:
<?php
$result = mysql_query($sql) or die(mysql_error()); // 經典模式
// 等價於:$result = (mysql_query($sql)) or die(...)
// 若查詢失敗 (false),執行 die()
// 實現三元運算符效果
$person = $who or $person = 'laruence';
// 等價:$person = empty($who) ? 'laruence' : $who;
?>
| 結合方向 | 運算符 |
|---|---|
| 無 | clone new |
[ (array) | |
| 右 | ** |
| 右 | ++ -- ~ (int) (float) (string) (array) (object) @ |
| 左 | * / % |
| 左 | + - . |
| 左 | << >> |
| 無 | < <= > >= |
| 無 | == != === !== <=> |
| 左 | & |
| 左 | ^ |
| 左 | | |
| 左 | && |
| 左 | || |
| 左 | ? : (三元) |
| 右 | = += -= *= /= .= %= &= |= ^= <<= >>= |
| 左 | and |
| 左 | xor |
| 左 | or |