Notice: Undefined variable: $var in /path/to/file.php on line 10
這是 **Notice** 級別錯誤,不會中斷執行,但代表程式碼邏輯缺陷:使用了從未賦值的變數。PHP 預設允許此行為 (視為 `null`),但會污染日誌、掩蓋真實 Bug。
<?php
// ❌ 錯誤:$bindata 未初始化直接串接
for ($i = 0; $i < strlen($hex); $i += 2) {
$bindata .= chr(hexdec(substr($hex, $i, 2)));
}
// ✅ 修正:迴圈前初始化
$bindata = '';
for ($i = 0; $i < strlen($hex); $i += 2) {
$bindata .= chr(hexdec(substr($hex, $i, 2)));
}
<?php
$sl = 'zh-CN';
$tl = 'en';
// ❌ 錯誤:函式內無法存取外部 $sl, $tl
function app_out($c, $gbk) {
$data = app_get_translate($c, $sl, $tl); // Undefined variable
...
}
// ✅ 修正 1:global 關鍵字 (不推薦,耦合全域狀態)
function app_out($c, $gbk) {
global $sl, $tl;
...
}
// ✅ 修正 2:參數傳遞 (推薦,明確相依)
function app_out($c, $gbk, string $sl, string $tl) {
$data = app_get_translate($c, $sl, $tl);
...
}
// ✅ 修正 3:閉包綁定 (PHP 7.4+ 箭頭函式自動捕獲)
$app_out = fn($c, $gbk) => app_get_translate($c, $sl, $tl);
<?php
// ❌ 錯誤:若 $condition 為 false,$result 未定義
if ($condition) {
$result = compute();
}
echo $result; // Notice
// ✅ 修正:預設值
$result = null;
if ($condition) {
$result = compute();
}
echo $result ?? 'N/A';
// ✅ 修正:三元運算子
$result = $condition ? compute() : null;
<?php
// ❌ 錯誤:$_POST 可能不含 'email'
$email = $_POST['email'];
// ✅ 修正:null 合併運算子 (PHP 7+)
$email = $_POST['email'] ?? '';
// ✅ 修正:isset/empty 檢查
$email = isset($_POST['email']) ? $_POST['email'] : '';
; php.ini (開發機)
error_reporting = E_ALL
display_errors = On
display_startup_errors = On
log_errors = On
error_log = /var/log/php/error.log
; php.ini (生產機)
error_reporting = E_ALL & ~E_DEPRECATED & ~E_STRICT
display_errors = Off
display_startup_errors = Off
log_errors = On
error_log = /var/log/php/error.log
<?php
// 檔案最開頭
error_reporting(E_ALL & ~E_NOTICE); // 隱藏 Notice (不推薦長期使用)
ini_set('display_errors', '1'); // 開發時開啟
ini_set('log_errors', '1');
ini_set('error_log', __DIR__ . '/logs/php_error.log');
<?php
declare(strict_types=1); // 嚴格型別模式,檔案最頂端
// 併用 PHPStan (composer require --dev phpstan/phpstan)
// phpstan.neon
parameters:
level: 5
paths:
- src
ignoreErrors:
- '#Unsafe usage of new static#' # 視專案調整
執行 `vendor/bin/phpstan analyse src` 即可在執行前攔截所有未定義變數、型別不符等問題。
「Undefined variable」不是小事,是代碼品質的警訊。養成**宣告即初始化**、**參數化相依**、**啟用嚴格模式**、**引入靜態分析**的習慣,才能寫出健壯、可維護的 PHP 程式。