How to try/catch a warning with PHP?

Spread the love

Sometimes, we want to try/catch a warning with PHP.

In this article, we’ll look at how to try/catch a warning with PHP.

How to try/catch a warning with PHP?

To try/catch a warning with PHP, we add a warning handler.

For instance, we write

set_error_handler("warning_handler", E_WARNING);
//...
restore_error_handler();

function warning_handler($errno, $errstr)
{
    // ...
}

to call set_error_handler with 'warning_handler' and E_WARNING to set the warning handler to the warning_handler function.

Then we can get the warning info from the parameters of the function.

Then we call restore_error_handler to restore the original warning handlers after we’re done running our code.

Conclusion

To try/catch a warning with PHP, we add a warning handler.

Leave a Reply

Your email address will not be published. Required fields are marked *