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?
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
orrequire
.