PHP 編譯器自上而下解析腳本,遇到第一個語法錯誤即停止並報告。報錯行號往往指向錯誤被發現的位置,而非真正錯誤位置(如少分號導致下一行報錯)。
Parse error: syntax error, unexpected T_IF in ... on line 4
典型原因:上一行缺少分號、括號不匹配、使用保留字做變量名($while = 1;)。
調試技巧:查看報錯行前幾行,檢查分號、引號、括號閉合。
Call to undefined function:函數名拼寫錯、擴展未載入、文件未包含。Class not found:類文件未載入、命名空間錯誤、自動加載失效。Maximum execution time exceeded:死循環或耗時操作,優化算法或調大 max_execution_time。Allowed memory size exhausted:內存洩漏、大數據集一次性讀入,改用生成器/分批處理。Undefined variable/index:使用未定義變量/數組鍵,開發階段應開啟 error_reporting(E_ALL) 盡早發現。Headers already sent:同 Session 錯誤,輸出在 Header 前。display_errors=On, error_reporting=E_ALL;生產環境 display_errors=Off, log_errors=On。var_dump 大法。tail -f /var/log/php-fpm/error.log 實時監控。git bisect 快速定位引入 Bug 的提交。<?php
$b = "somevalue" // 第 2 行缺少分號
if ($b == "somevalue") { // 第 3 行
print "Hello world!";
}
?>
// 報錯:Parse error: unexpected T_IF on line 3
// 真正錯誤在 line 2 末尾
編譯器解析完 $b = "somevalue" 以為語句未結束,繼續吞噬 if 關鍵字,發現語法無效才在 if 所在行報錯。