fabjoa
fabjoa

Reputation: 51

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 cannot retrieve file, line and stack context.

Upvotes: 5

Views: 9201

Answers (2)

Wh1T3h4Ck5
Wh1T3h4Ck5

Reputation: 8509

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. "

Upvotes: 1

Gaurav
Gaurav

Reputation: 28755

You can use require_once instead of include_once

Upvotes: 2

Related Questions