Search code examples
phperror-handlingphp-7error-loggingerror-log

How to Use the Static function of Custom Error Logging in PHP


I'm having a custom Static Error Logging method, as specified in the following link http://www.bbminfo.com/Tutor/php_error_error_log.php I executed the code as mentioned in the tutorial, I'm getting the output as expected. But now I moved the error handing method to a class and I made it as Static. I facing an issue its not working

class ErrorHandling {

    /* Error Handling Function */
    public static function bbmNotice($errNo, $errStr, $errFile, $errLine) {
        $error_msg = "Custom PHP Notice : " . $errNo . "\n";
        $error_msg .= "Message : " . $errStr . "\n";
        $error_msg .= "Location : " . $errFile . "\n";
        $error_msg .= "Line Number : " . $errLine . "\n";

        /* Error Logging in General error_log File*/
        error_log($error_msg, 0);
    }

    /* Error Handler Fixing */
    set_error_handler("bbmNotice", E_USER_NOTICE);

}


/* Undefined Variable: $str */
if(isset($str)) {
    echo $str ;
} else {
    trigger_error("Variable 'str' is not defined, Kindly define the variable 'str' before usage.", E_USER_NOTICE);
} 

I'm getting the following error

Parse error: syntax error, unexpected 'set_error_handler' (T_STRING), expecting function (T_FUNCTION) in /home2/bbminfon/public_html/error.php on line 17

Kindly assist me how to log the error in this setup.


Solution

  • The parse error occurs because you are trying register a function as error handler, but actually want to register a class method.

    Register the error handler like this instead:

    class ErrorHandling 
    {
        /* Error Handling Function */
        public static function bbmNotice($errNo, $errStr, $errFile, $errLine)
        {
            $error_msg = "Custom PHP Notice : " . $errNo . "\n";
            $error_msg .= "Message : " . $errStr . "\n";
            $error_msg .= "Location : " . $errFile . "\n";
            $error_msg .= "Line Number : " . $errLine . "\n";
    
            /* Error Logging in General error_log File*/
            error_log($error_msg, 0);
        }
    }
    
    
    set_error_handler("ErrorHandling::bbmNotice", E_USER_NOTICE);
    

    For reference, see: