在 PHP 中,Catch 不能与 require_once 一起使用?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5369488/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Try Catch cannot work with require_once in PHP?
提问by user310291
I can't do something like this ?
我不能做这样的事情吗?
try {
require_once( '/includes/functions.php' );
}
catch(Exception $e) {
echo "Message : " . $e->getMessage();
echo "Code : " . $e->getCode();
}
No error is echoed, server returns 500.
没有回显错误,服务器返回 500。
回答by a1ex07
You can do it with include_once
or file_exists
:
你可以用include_once
或来做到file_exists
:
try {
if (! @include_once( '/includes/functions.php' )) // @ - to suppress warnings,
// you can also use error_reporting function for the same purpose which may be a better option
throw new Exception ('functions.php does not exist');
// or
if (!file_exists('/includes/functions.php' ))
throw new Exception ('functions.php does not exist');
else
require_once('/includes/functions.php' );
}
catch(Exception $e) {
echo "Message : " . $e->getMessage();
echo "Code : " . $e->getCode();
}
回答by Nanne
As you can read here: (emph mine)
正如你可以在这里读到的:(我的)
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
require() 与 include() 相同,除了失败时它还会产生一个致命的 E_COMPILE_ERROR 级别错误。换句话说,它将停止脚本
This is about require, but that is equivalent to require_once(). This is not a catchable error.
这是关于 require 的,但这相当于 require_once()。这不是一个可捕获的错误。
By the way, you need to enter the absolute path, and I don't think this is right:
顺便说一句,你需要输入绝对路径,我认为这是不对的:
require_once( '/includes/functions.php' );
You might want something like this
你可能想要这样的东西
require_once( './includes/functions.php' );
Or, if you're calling this from a subdir or from a file that is included in different dirs, you might need something like
或者,如果您从子目录或包含在不同目录中的文件调用它,则可能需要类似
require_once( '/var/www/yourPath/includes/functions.php' );
回答by Justin
This should work, but it is a bit of a hack.
这应该有效,但它有点黑客。
if(!@include_once("path/to/script.php")) {
//Logic here
}