set_error_handler 関数
関数 set_error_handler は、ユーザー定義エラーハンドラを設定します。
最初のパラメータには、エラー発生時に呼び出されるコールバック関数を渡します。
2番目のオプションパラメータでは、ハンドラが捕捉するエラーの種類を指定できます。
構文
set_error_handler(callable $error_handler, int $error_types = E_ALL | E_STRICT);
例
ユーザー定義エラーハンドラのシンプルな例:
<?php
function customError($errno, $errstr, $errfile, $errline) {
echo "Error [$errno]: $errstr in $errfile on line $errline";
}
set_error_handler("customError");
echo $undefinedVar;
?>
コード実行結果:
Error [8]: Undefined variable: undefinedVar in /path/to/file.php on line 7
例
特定の種類のエラーのみを処理する:
<?php
function warningHandler($errno, $errstr) {
if ($errno === E_WARNING) {
echo "Warning captured: $errstr";
}
}
set_error_handler("warningHandler", E_WARNING);
strpos(); // 警告を引き起こす
?>
コード実行結果:
Warning captured: strpos() expects at least 2 parameters, 0 given
例
標準エラーハンドラに戻す:
<?php
set_error_handler(null); // 標準ハンドラに戻す
?>