register_shutdown_function is not getting called

4.7k views Asked by At

This is a snippet from my original code I am testing to handle error.

The FIRST approach is calling the fatalErrorHandler(), but the SECOND approach is not calling the fatalErrorHandler(). What could be the reason?

FIRST

<?php 
//error_reporting(0);

function fatalErrorHandler() {
    echo 'YAY IT WORKED';
}

# Registering shutdown function
register_shutdown_function('fatalErrorHandler');

// let force a Fatal error -- function does not exist
functiontest();

echo "hello";

?>

output:

Fatal error: Call to undefined function functiontest() in ...test2.php on line 12 YAY IT WORKED

SECOND

 <?php 
    //error_reporting(0);

    function fatalErrorHandler() {
        echo 'YAY IT WORKED';
    }

    # Registering shutdown function
    register_shutdown_function('fatalErrorHandler');

    // let force a Fatal error -- function does not exist
    functiontest();

    function foo () {

    }

    function foo() {

    }

    echo "hello";

    ?>

Output:

Fatal error: Cannot redeclare foo() (previously declared in ...test/test2.php:16) in ../test2.php on line 20

fatalErrorHandler is not getting called in this scenario. why?

2

There are 2 answers

3
Halcyon On BEST ANSWER

In PHP you can use a function before you define it. I think this means that the interpreter must parse all functions before it starts execution. So register_shutdown_function is not yet called when this error is detected.

You could test this by moving the duplicate function definition into a separate file and including it with include or require.

0
Andrei On

I think it's about compiling order. See the condition.

Take a look at this example:

// The shutdown function won't be called
register_shutdown_function(function(){
    echo "I'm in!";
});
function test(){}
function test(){}

And now at this example:

// The shutdown function will be called
register_shutdown_function(function(){
    echo "I'm in!";
});
function test(){}
if(1 === 1)
{
    function test(){}
}