The set_error_handler function lets you control what happens when an error occurs in your PHP program. Instead of showing the default error message, you can create your own way to handle errors.
Set_error_handler function in PHP
set_error_handler(callable $error_handler, int $error_levels = E_ALL): ?callable
The $error_handler is a function you create that will run when an error happens.
The optional $error_levels lets you choose which errors to catch (default is all errors).
<?php function myErrorHandler($errno, $errstr, $errfile, $errline) { echo "Error [$errno]: $errstr in $errfile on line $errline\n"; } set_error_handler('myErrorHandler');
<?php set_error_handler(function($errno, $errstr) { echo "Custom error: $errstr\n"; });
<?php
set_error_handler('myErrorHandler', E_WARNING | E_NOTICE);This program sets a custom error handler that prints a friendly message when an error happens. Then it causes two errors: dividing by zero and using an undefined variable. Instead of default errors, the custom messages show.
<?php function customErrorHandler($errno, $errstr, $errfile, $errline) { echo "Oops! Error number $errno happened: $errstr on line $errline in file $errfile\n"; } set_error_handler('customErrorHandler'); // This will cause a warning (division by zero) echo 10 / 0; // This will cause a notice (undefined variable) echo $undefinedVar;
The error handler function must accept at least four parameters: error number, error message, file name, and line number.
After setting a custom error handler, PHP will use it for errors matching the specified levels.
Remember to restore the original error handler if needed using restore_error_handler().
set_error_handler lets you catch and handle errors your way.
You create a function that runs when an error happens.
This helps make your program friendlier and easier to debug.