在 PHP 中的导入函数中了解实际代码中断的位置
Know where the Actual Code Broke In an imported function in PHP
例如,我有一个包含函数的简单包含文件:
function ViewInclude($file){
require_once $file.'.inc.php';
}
并且,另一个使用函数的文件(比如 index.php):
require_once 'inc.php';
ViewInclude('header');
当require
失败时,警告信息如下:
Warning: require_once(header.inc.php): failed to open stream:
No such file or directory in ..../tests/inc.php on line 4
现在,比方说,其他一些文件也包含 inc.php
文件。当 require
失败时,错误是 at inc.php at some line.
有没有办法知道触发错误的实际文件和行号? (我的意思是包含错误起源的地方。在上面的例子中是这样的:at index.php at line 62)
您可以使用 debug_backtrace
function to see the history of how the script got to that point. Use a try
/catch
block or set_error_handler
来捕获错误。
类似这样的内容可能会有所帮助:
function ViewInclude($file){
if (file_exists($file)) {
include_once($file);
} else {
$debug = debug_backtrace()[0];
echo 'Failed to include file in '.$debug['file'].
' at line '.$debug['line'].'<br />';
}
}
例如,我有一个包含函数的简单包含文件:
function ViewInclude($file){
require_once $file.'.inc.php';
}
并且,另一个使用函数的文件(比如 index.php):
require_once 'inc.php';
ViewInclude('header');
当require
失败时,警告信息如下:
Warning: require_once(header.inc.php): failed to open stream: No such file or directory in ..../tests/inc.php on line 4
现在,比方说,其他一些文件也包含 inc.php
文件。当 require
失败时,错误是 at inc.php at some line.
有没有办法知道触发错误的实际文件和行号? (我的意思是包含错误起源的地方。在上面的例子中是这样的:at index.php at line 62)
您可以使用 debug_backtrace
function to see the history of how the script got to that point. Use a try
/catch
block or set_error_handler
来捕获错误。
类似这样的内容可能会有所帮助:
function ViewInclude($file){
if (file_exists($file)) {
include_once($file);
} else {
$debug = debug_backtrace()[0];
echo 'Failed to include file in '.$debug['file'].
' at line '.$debug['line'].'<br />';
}
}