确定“;“冒犯”;发生错误时的文件和行号


Determine the "offending" file and line number when error occurs

这有点难以解释,但代码可能更清晰:

// class.php
class Foo
{
    public function bar ()
    {
    }
}

// test.php
$foo = new Foo;
$foo->bar(); // e.g., for some reason this returns an error hence error handler will be triggered

这是一个简化的示例,但test.php的嵌套可能更深。我的自定义错误处理程序如何告诉我错误发生在test.php第2行?

我目前正在使用debug_backtrace(),但test.php的数组索引会根据对象的深度或require()的数量而变化

无论函数调用的嵌套有多深,有没有一种方法可以精确定位这一点?

您可以打印一个debug_backtrace(),它将生成所有调用方的完整数组,包括文件和行号。

示例

<?php
    class Test {
        public function debug() {
            print_r(debug_backtrace());
        }
    }
    function print_debug() {
        $test = new Test();
        $test->debug();
    }
    header("Content-type: text/plain");
    print_debug();

结果

Array
(
    [0] => Array
        (
            [file] => D:'Websites'htdocs'tests'index.php
            [line] => 11
            [function] => debug
            [class] => Test
            [object] => Test Object
                (
                )
            [type] => ->
            [args] => Array
                (
                )
        )
    [1] => Array
        (
            [file] => D:'Websites'htdocs'tests'index.php
            [line] => 14
            [function] => print_debug
            [args] => Array
                (
                )
        )
)

你也可以尝试抛出一个异常,并允许它冒泡,它会杀死你的脚本,显示一个完整的回溯。看看这对你是否有效。