Search code examples
phperror-reporting

Why no PHP error on call to undefined function?


Whenever there is a call to an undefined function, no errors are logged. Instead the script just stops executing. To make things worse, if I run php -l filename.php, It shows that there are no syntax errors. I am using a custom error handler function, but even the first line is never reached.

How can I get it to run my error handler when there is a call to an undefined function?

I am using PHP 5.3.2-1. Here is the code that is setting the error handler:

error_reporting(-1);
$old_error_handler = set_error_handler( "userErrorHandler" );
set_exception_handler('exception_handler');

Neither the error handler nor the exception handler are being reached, although they do work for other errors.

The reason I want this is I end up having to place debug statements in my code to see how far it gets before it stops executing which is a slow process compared to an error message that would tell me the file and line number where the error is.


Solution

  • Fatal errors can not be caught by a user error handler.

    See http://php.net/manual/en/function.set-error-handler.php

    Specifically the part:

    The following error types cannot be handled with a user defined function: E_ERROR, E_PARSE, E_CORE_ERROR, E_CORE_WARNING, E_COMPILE_ERROR, E_COMPILE_WARNING, and most of E_STRICT raised in the file where set_error_handler() is called.

    And as per the comments on the PHP manual page, one work around is to test for errors in the shutdown function:

    <?php
        error_reporting(E_ALL);
        ini_set('display_errors', 0);
    
        function shutdown(){
            $isError = false;
            if ($error = error_get_last()){
                switch($error['type']){
                    case E_ERROR:
                    case E_CORE_ERROR:
                    case E_COMPILE_ERROR:
                    case E_USER_ERROR:
                        $isError = true;
                        break;
                }
            }
    
            if ($isError){
                echo "Script execution halted ({$error['message']})";
            } else {
                echo "Script completed";
            }
        }
    
        register_shutdown_function('shutdown');
    ?>