網路上流傳的「取得變數名稱」函數利用 $GLOBALS 遍歷比對值,但若直接用 == 鬆散比較,會導致字串 "hello" 與整數 0 判定相等,造成錯誤回傳變數名。本文詳細分析此 Bug 並給出修正版。
<?php
function getVarName(&$src) {
$save = $src;
$allvar = $GLOBALS;
foreach ($allvar as $k => $v) {
if ($src == $v) { // ❌ 鬆散比較:字串 "hello" == 0 為 true
$src = 'change';
if ($src == $GLOBALS[$k]) {
$src = $save;
return $k;
}
}
}
return null;
}
?>
<?php
$test2 = "hello";
$countNum = 0;
echo getVarName($test2); // 預期 "test2",實際輸出 "countNum" ❌
/* 原因:
1. 循環到 $countNum (值 0) 時,$src="hello"
2. "hello" == 0 → true (字串轉整數為 0)
3. 進入 if,修改 $src = 'change'
4. $GLOBALS['countNum'] 仍為 0,'change' == 0 → true
5. 錯誤回傳 'countNum'
*/
?>
<?php
function getVarNameCorrect(&$src): ?string {
$save = $src;
foreach ($GLOBALS as $k => $v) {
if ($src === $v) { // ✅ 嚴格比較:型別與值皆相同
$src = '___UNIQUE_MARKER___'; // 用極低機率字串避免衝突
if ($src === $GLOBALS[$k]) {
$src = $save;
return $k;
}
$src = $save; // 還原繼續找 (理論上不會有第二個同引用)
}
}
return null;
}
?>
<?php
$test2 = "hello";
$countNum = 0;
$another = "hello"; // 同值不同變數
echo getVarNameCorrect($test2); // 輸出 "test2" ✅
echo "\n";
echo getVarNameCorrect($countNum); // 輸出 "countNum" ✅
echo "\n";
echo getVarNameCorrect($another); // 輸出 "another" ✅ (第一個匹配到的)
?>
==:型別轉換後比較值。"hello" == 0 → true (字串轉 int 為 0)。===:不轉型,型別與值皆相同才為 true。"hello" === 0 → false。$a=1; $b=1; 傳入 $a 可能回傳 "b" (看遍歷順序)。debug_backtrace() 解析呼叫堆疊、var_name() (PHP 8.2+ ReflectionVariable::getName())、或重構代碼避免需要知道變數名 (通常是設計味道)。
<?php
// PHP 8.2+ 新增 ReflectionVariable::getName()
function getVarNameModern(mixed &$var): string|false {
try {
$ref = new ReflectionVariable($var);
return $ref->getName();
} catch (ReflectionException) {
return false;
}
}
$x = 123;
echo getVarNameModern($x); // "x" ✅
?>