PHP intercepts fatal error instance

*文
Release: 2023-03-18 15:26:02
Original
1522 people have browsed it

How does PHP intercept fatal errors? This article mainly introduces examples of using the register_shutdown_function function to intercept fatal errors in PHP. I hope to be helpful.

When we are working on projects, fatal errors occasionally occur due to carelessness. If display_errors is set to off, the user will see a blank page. If it is set to on, the fatal error information will be displayed (of course, normal people will not do this).

So is there any way we can intercept the fatal error in advance and feedback it to the user in our own custom friendly form? There is a function in PHP called register_shutdown_function that allows us to set another function that can be called when the execution is shut down. That is to say, when our script execution is completed or unexpectedly dies and the PHP execution is about to shut down, this function will is called.
Please see an example below:

<?php
$flag = false;
function deal_error(){
    global $flag;
    if (!$flag){
        die("粗问题啦,请稍后再试");
    }
    return false;
}
register_shutdown_function("deal_error");
//将因为致命错误而失败
//$obj = new NotExistClass(); //引入未定义的类
require(&#39;./test.php&#39;);
$flag = true;
Copy after login


We set the flag to false at the program entry, and finally set it to true, indicating that the program is executed normally. If the flag is not true at the end, it means it died somewhere in the middle. At this time, register_shutdown_function will be called to output our customized error result.

If the above class is not defined, non-existent files are introduced (require or require_once must be used), etc., it will lead to fatal errors. Of course, if your program is missing a punctuation mark or has an extra special character or something, then there is nothing you can do.

Related recommendations:

php Detailed explanation of error types and shielding methods

php Detailed explanation of error handling mechanism examples

php Error message configuration

The above is the detailed content of PHP intercepts fatal error instance. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template