首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 相關知識

PHP 中 OR 運算子的優先級陷阱與短路特性實例解析

     編輯:PHP 相關知識

核心差異:|| vs or

|| 優先級高於賦值(=),or 優先級低於賦值。導致同樣邏輯賦值結果截然不同。

代碼實驗

$choice1 = "wdphp.com";
$choice2 = "";
$default = "vducn.com";

$val_1 = $choice1 || $choice2 || $default; // 邏輯運算結果:true(1)
$val_2 = $choice1 or $choice2 or $default; // 賦值結果:$choice1 的值 "wdphp.com"
$val_3 = ($choice1 or $choice2 or $default); // 括號提升優先級:true(1)

echo "val_1=$val_1 val_2=$val_2 val_3=$val_3";
// 輸出:val_1=1 val_2=wdphp.com val_3=1

函數回傳值配合 or 的行為

function foo() { return 0; }
function bar() { return 1; }

$x_1 = foo() or bar(); // $x_1 = 0 (foo 的回傳值)
$x_2 = $x_1 or bar();  // $x_2 = 0 ($x_1 的值)
$x_3 = ($x_1 or bar()); // $x_3 = 1 (邏輯運算結果)

echo "x_1=$x_1 x_2=$x_2 x_3=$x_3";
// 輸出:x_1=0 x_2=0 x_3=1

替代 if 的寫法

is_array($variable) or notAnArray();
function notAnArray() { echo "This is not an array"; }

利用短路特性:左側為假才執行右側。僅適用於簡單邏輯,複雜流程請用 if/else 保持可讀性。

總結

  • 邏輯判斷用 ||、&&。
  • 流程控制、賦值預設值可用 or、and,但需完全理解優先級。
  • 建議統一使用括號明確意圖,避免隱性 Bug。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved