w3resource

PHP error handling functions - set_error_handler()

Description 

The set_error_handler() function is used to set a user-defined  error handling function.

Version:

PHP 4.0.1, PHP 5

Syntax:

set_error_handler (error_handler, error_types)

Parameter:

Parameters Description Required / Optional Type
error_handler Specifies the function to be run at errors. Contains : errorno  - An integer indicating the level of the error. errstr - A string which contains the error message. errfile  - A string which contains the filename that the error was raised in. This is optional. errline - An integer indicating the line number the error was raised at. This is optional. errcontext - This is an array which contains all the variables that existed in the scope the error was triggered in. This is optional. Required callback
error_types Purpose of this parameter is to mask the triggering of the error_handler function resembling the error_reporting ini setting controls which are to be shown. If not used, error_handler is called for every error irrespective of the setting of the error_reporting setting. Required integer

Return Values

The function returns a string which contains the previously defined error handler. But it returns NULL if the built-in error handler is used instead of a user defined one. In the case of an error resembling to invalid callback, the function returns NULL. If the user defined error handler used previously was a class method, the function returns an indexed array containing the name of the class and method.

Example :

 <?php
    function w3r_notice($no, $str, $file, $line) {
        echo "Encountered notice $no in $file, line $line: $str\n";
    }
    function func_error($num, $str, $file, $line) {
        echo "Encountered error $num in $file, line $line: $str\n";
    }
    set_error_handler("w3r_notice", E_NOTICE);
    set_error_handler("w3r_error", E_ERROR);
    echo $demo;
?>

Previous: restore_exception_handler()
Next: set_exception_handler()



PHP: Tips of the Day

PHP: How to convert string to boolean?

Strings always evaluate to boolean true unless they have a value that's considered "empty" by PHP (taken from the documentation for empty):

  1. "" (an empty string);
  2. "0" (0 as a string)

If you need to set a boolean based on the text value of a string, then you'll need to check for the presence or otherwise of that value.

$test_mode_mail = $string === 'true'? true: false;

EDIT: the above code is intended for clarity of understanding. In actual use the following code may be more appropriate:

$test_mode_mail = ($string === 'true');

or maybe use of the filter_var function may cover more boolean values:

filter_var($string, FILTER_VALIDATE_BOOLEAN);

filter_var covers a whole range of values, including the truthy values "true", "1", "yes" and "on".

Ref : https://bit.ly/33SQ3eP