try catch a failed include
This is a simple question one hour of Googling do not seem to solve. How do you catch a failed include in PHP? For the following code:
try {
include_once 'mythical_file';
} catch (Exception $e) {
exit('Fatal');
}
echo '?';
With mythical_file not existing, I get the output '?'. I know PHP can not catch failed required because it triggers a Warning Error, but here? What is the best way to catch a failed include? For example, the following works:
(include_once 'unicorn') or exit('!');
but it does not trigger an exception so I开发者_C百科 cannot retrieve file, line and stack context.
You can use require_once
instead of include_once
include and include_once trigger warning (E_WARNING), require and require_once trigger error (E_COMPILE_ERROR). So you should use require
or require_once
.
php.net quote:
"require() is identical to include() except upon failure it will also produce a fatal E_COMPILE_ERROR level error. In other words, it will halt the script whereas include() only emits a warning (E_WARNING) which allows the script to continue. "
精彩评论