Hàm set_error_handler
Hàm set_error_handler thiết lập một bộ xử lý lỗi tùy chỉnh.
Tham số đầu tiên được truyền vào là một hàm callback, hàm này sẽ được gọi khi có lỗi xảy ra.
Tham số thứ hai không bắt buộc có thể dùng để chỉ định các loại lỗi mà bộ xử lý sẽ chặn.
Cú pháp
set_error_handler(callable $error_handler, int $error_types = E_ALL | E_STRICT);
Ví dụ
Một ví dụ đơn giản về bộ xử lý lỗi tùy chỉnh:
<?php
function customError($errno, $errstr, $errfile, $errline) {
echo "Lỗi [$errno]: $errstr trong $errfile tại dòng $errline";
}
set_error_handler("customError");
echo $undefinedVar;
?>
Kết quả thực thi mã:
Lỗi [8]: Undefined variable: undefinedVar trong /path/to/file.php tại dòng 7
Ví dụ
Chỉ xử lý các loại lỗi cụ thể:
<?php
function warningHandler($errno, $errstr) {
if ($errno === E_WARNING) {
echo "Đã chặn cảnh báo: $errstr";
}
}
set_error_handler("warningHandler", E_WARNING);
strpos(); // Sẽ gây ra cảnh báo
?>
Kết quả thực thi mã:
Đã chặn cảnh báo: strpos() expects at least 2 parameters, 0 given
Ví dụ
Khôi phục bộ xử lý lỗi mặc định:
<?php
set_error_handler(null); // Khôi phục về bộ xử lý mặc định
?>