萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 運算符優先級陷阱與核心機制深度解析

經典陷阱案例

<?php
if ($a = 100 && $b = 200) {
    var_dump($a, $b);
}
// 輸出:bool(true) int(200)
// 而非預期的 int(100) int(200)
?>

為什麼會這樣?優先級 ≠ 結合順序

雖然 `=` 優先級低於 `&&`,但 PHP 解析器有特殊規則:當 `=` 左側是變數,右側包含 `&&`/`||` 時,允許右側表達式優先結合。實際解析為:

$a = (100 && ($b = 200))

步驟:

  1. `$b = 200` 執行,返回 200 (truthy)。
  2. `100 && 200` → `true`。
  3. `$a = true`。

這違背直覺的優先級預期 `(($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 / xor

and / 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

避坑指南

  1. 賦值表達式中避免使用 `&&`/`||`,改用 `and`/`or` 或拆分語句。
  2. 複雜條件加括號:`if (($a = 100) && ($b = 200))` 明確意圖。
  3. 熟記 `and`/`or` 低優先級特性,善用於流程控制鏈(如 `$fp = fopen(...) or die();`)。
  4. 三元運算符 `?:` 優先級在賦值之上,嵌套時必加括號。
copyright © 萬盛學電腦網 all rights reserved