Last updated: November 25, 2026.
On PHP 8, a custom error handler receives the error level, message, filename and line number. Remove the fifth $errcontext parameter from older handlers. If the callback requires it, PHP can raise an argument-count error when it tries to report the original problem.
<?php
set_error_handler(
static function (int $level, string $message, string $file, int $line): bool {
if (!(error_reporting() & $level)) {
return false;
}
error_log("Warning at $file:$line: $message");
return true;
},
E_USER_WARNING
);
try {
trigger_error('Example application warning', E_USER_WARNING);
} finally {
restore_error_handler();
}Use the four arguments PHP supplies
The first two arguments identify what happened. The filename and line number identify where the warning originated. You can declare fewer parameters if you only need the level and message. The = ? notation shown in the manual is documentation notation and is not valid default-value syntax in a callback declaration.
If an older callback used the context array for logging, pass the specific diagnostic data to your application logger at the call site. That gives you control over what gets recorded and avoids logging unrelated variables or credentials.
Choose which warnings to intercept
The second argument to set_error_handler() selects which error levels invoke your callback. This example handles user-generated warnings so the behavior is easy to demonstrate. If the callback returns false, PHP falls back to its standard handler. The explicit error_reporting() check lets that standard behavior apply when the current reporting mask excludes the level.
Use finally to restore the previous handler even if the operation throws. Exceptions still follow their own handling path. Some errors, including parse failures in the script itself, also fall outside the user error handler’s scope.