@ 放在表達式前,抑制該表達式產生的錯誤訊息輸出(Notice、Warning、Deprecated 等),但不改變錯誤發生事實,也不阻止異常拋出。
<?php
function div($a, $b) {
return $a / $b;
}
echo @div(10, 0); // 不顯示 "Division by zero Warning"
echo "腳本繼續執行\n"; // 正常輸出
// 自定義錯誤處理
set_error_handler(function($severity, $message, $file, $line) {
if (!(error_reporting() & $severity)) return false; // @ 生效時 error_reporting() 為 0
throw new ErrorException($message, 0, $severity, $file, $line);
});
try {
@div(10, 0); // 錯誤被抑制,不進入 handler
} catch (ErrorException $e) {
echo "捕獲異常: " . $e->getMessage();
}
?>
| 場景 | 代碼 | 備註 |
|---|---|---|
| 檔案操作可能失敗 | @$content = file_get_contents($path); | 檔案不存在時不報 Warning |
| 資料庫連線 | @$pdo = new PDO(...); | 連線失敗自行檢查 $pdo 或 catch Exception |
| 陣列鍵可能不存在 | $val = @$arr['key']; | 較 isset() 簡潔但效能差 |
| 載入外部資源 | @include 'config.local.php'; | 檔案不存在不報錯 |
error_reporting、建立錯誤上下文,比 isset() 慢 10-100 倍set_error_handler(),@ 仍會呼叫 handler,需在 handler 內檢查 error_reporting() === 0 判斷是否被抑制<?php
// 取陣列值,不存在給預設
$val = $arr['key'] ?? 'default';
// 多層級
$val = $data['user']['profile']['name'] ?? 'anonymous';
// 需 PHP 7.4+ ?-> 安全導航
$val = $data?->user?->profile?->name ?? 'anonymous';
?>
<?php
// 檔案讀取
if (is_readable($path)) {
$content = file_get_contents($path);
} else {
$content = '';
// 記錄日誌、拋異常
}
// PDO 連線:本身拋出 PDOException,用 try-catch
try {
$pdo = new PDO($dsn, $user, $pass, [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
} catch (PDOException $e) {
log_error($e);
show_friendly_error();
}
?>
<?php
// 全域錯誤轉異常(開發/測試環境)
set_error_handler(function($severity, $message, $file, $line) {
if (error_reporting() & $severity) {
throw new ErrorException($message, 0, $severity, $file, $line);
}
});
// 生產環境:自定義 handler 記錄日誌、顯示友好頁面
set_exception_handler(function(Throwable $e) {
http_response_code(500);
log_error($e);
include 'templates/500.php';
exit;
});
?>
@unlink($tempFile) 清理暫存檔@ 是「止痛藥」而非「治療藥」。現代 PHP 開發應以預防性檢查、異常處理、類型系統 替代,保持代碼清晰、可維護、可觀測。