代碼不符合 PHP 語法規則,腳本無法執行,直接拋出 Parse Error。
<?php
Echo 100. // 缺少分號
Echo 100;
Echo 101;
?>
// Parse error: syntax error, unexpected ';'
腳本能運行,但因邏輯或環境問題導致功能失效,輸出 Warning/Notice,不中止腳本。
<?php
echo "this is a demo";
header('Location: https://www.example.com/'); // header 前有輸出
?>
// Warning: Cannot modify header information - headers already sent
腳本正常運行且無報錯,但結果不符合預期,最難排查。
<?php
$a = 5;
if ($a = 6) { // 應為 ==,這裡是賦值
echo $a; // 輸出 6
}
?>
<?php
// 顯示所有錯誤
error_reporting(E_ALL);
ini_set('display_errors', 1);
// 生產環境建議關閉顯示,記錄日誌
// ini_set('display_errors', 0);
// ini_set('log_errors', 1);
// ini_set('error_log', '/path/to/php-error.log');
?>
PHP 5+ 引入異常機制,可用 try-catch 捕獲可預期的運行時異常,配合自定義異常類實現優雅錯誤處理。
<?php
try {
// 高風險操作
if (!$conn = @mysqli_connect(...)) {
throw new Exception('資料庫連接失敗');
}
} catch (Exception $e) {
error_log($e->getMessage());
die('系統繁忙,請稍後再試');
}
?>