遞迴函數在基底條件滿足時正確 return,但在遞迴呼叫處忘記加 return,導致最終呼叫者收到 null 而非預期值。
<?php
function test($i) {
$i -= 4;
if ($i < 3) {
return $i; // 基底條件:正確回傳
} else {
test($i); // ❌ 遞迴呼叫缺少 return!
}
}
echo test(30); // 輸出空白 (null)
?>
執行流程:test(30) → test(26) → ... → test(2) → return 2,但每一層呼叫者未接收回傳值繼續向上傳遞,最外層 `test(30)` 隱性回傳 `null`。
<?php
function test($i) {
$i -= 4;
if ($i < 3) {
return $i;
} else {
return test($i); // ✅ 加上 return 向上傳遞
}
}
echo test(30); // 輸出: 2
?>
遞迴函數每一層呼叫都必須
return遞迴結果,確保值層層傳遞回最頂層呼叫者。
<?php
// 收集所有節點路徑
function findPaths($node, $path = '') {
$path .= $node->name . '/';
if (empty($node->children)) {
return [$path]; // 基底:回傳陣列
}
$result = [];
foreach ($node->children as $child) {
// ✅ 合併遞迴結果
$result = array_merge($result, findPaths($child, $path));
}
return $result;
}
error_log() 追蹤呼叫深度與回傳值。遞迴函數缺少 return 是最常見且隱蔽的 Bug。養成「遞迴呼叫前必加 return」肌肉記憶,並配合單元測試驗證回傳值正確性,能徹底避免此類問題。