我需要捕获函数"include" PHP的最后一个错误。
我用"Exceptions"函数进行测试,但不幸的是,我在上面写了函数"include"。
如果我在函数后面写"include"不显示异常
示例1:
try{
throw new exception();
require_once( $this->controller['path'] );
}
catch( exception $e )
{
print_r( error_get_last() );
}
This Return:…(Void)…
示例2:
try{
require_once( $this->controller['path'] ) OR throw new exception();;
}
catch( exception $e )
{
print_r( error_get_last() );
}
This return: Parse error: syntax error, unexpected T_THROW in…
我故意在文件中创建了一个语法错误来包含。其思想是捕获错误,以便您可以调试它们。
有人知道怎么得到这个吗?
的家伙!我需要捕捉语法错误。问候!
首先,如果你使用require
,如果文件不能包含,它总是会杀死你的应用程序。你无法控制结果,之后你什么也做不了。如果您想要控制文件包含的成功,请使用include
并测试其返回值。
$success = include "foo.php";
if (!$success) {
// the file could not be included, oh noes!
}
你可以有语法上的不同,比如:
if (!(include "foo.php")) ...
这个将触发一个E_NOTICE
如果文件不能被包含,你不能捕获。但是没关系,因为它将帮助您调试问题,并且在生产环境中错误显示将被关闭(对,right?)。
or throw new Exception
不能工作,因为throw
是一个语句,不能在需要表达式的地方使用。
如果您想捕获包含的文件中的语法错误,请使用php_check_syntax
/它的继任者php -l <file>
。
require_once
是一个语言结构,而不是一个函数,你不能用它做短路。
要在包含文件之前测试该文件是否存在,可以使用is_file()
。如果您想测试文件是否可读,您可以使用is_readable()
。
您可能还想使用include
,如果找不到文件,它会发出E_WARNING
,而不是E_COMPILE_ERROR
。
我同意alex的观点,尝试通过检查file_exists()
来捕获错误,然后使用Exception
if(file_exists($this->controller['path'])){
try{
require_once( $this->controller['path'] );
}catch(Exception $e){
// throw error
}
}
或使用is_readable()
if(is_readable($this->controller['path'])){
try{
require_once( $this->controller['path'] );
}catch(Exception $e){
// throw error
}
}
大多数本地PHP函数触发错误而不是抛出异常。要将PHP错误转换为异常,可以设置一个自定义错误处理程序:
function exceptions_error_handler($severity, $message, $filename, $lineno) {
throw new ErrorException($message, 0, $severity, $filename, $lineno);
}
set_error_handler('exceptions_error_handler');
使用这段代码,您将能够捕获所有非致命错误作为异常。注意,require_*
函数抛出致命错误,因此您必须使用include
。至于在代码本身中处理语法错误,如果你稍微考虑一下,这是完全不可能的。