记录所有执行的行

Ben*_*ams 10 php

让PHP将每条执行的行写入日志有一种简单的方法(在每一行之后没有坚持的写法)吗?

net*_*der 17

虽然我同意@gnif,因为调试器最适合它,我仍然会回答你的问题,因为它是可能的(不完美,但可能).

考虑您有以下代码:

sometest.php

<?php

declare(ticks=1);

include_once 'debug.php';

$a = 'foo';
$b = 'bar';
$c = $a . $b;
$d = $e = "hello";
strlen($d);

include 'somefile.php';
Run Code Online (Sandbox Code Playgroud)

somefile.php

<?php

$hello = 'world';
Run Code Online (Sandbox Code Playgroud)

因此,sometest.php包括以下文件(debug.php):

<?php

register_tick_function(function(){
    $backtrace = debug_backtrace();
    $line = $backtrace[0]['line'] - 1;
    $file = $backtrace[0]['file'];

    if ($file == __FILE__) return;

    static $fp, $cur, $buf;
    if (!isset($fp[$file])) {
        $fp[$file] = fopen($file, 'r');
        $cur[$file] = 0;
    }

    if (isset($buf[$file][$line])) {
        $code = $buf[$file][$line];
    } else {
        do {
            $code = fgets($fp[$file]);
            $buf[$file][$cur[$file]] = $code;
        } while (++$cur[$file] <= $line);
    }

    $line++;
    echo "$code called in $file on line $line\n";
});
Run Code Online (Sandbox Code Playgroud)

注册了一个tick函数,并且还声明了tick时间间隔.它将跟踪使用回溯调用的文件/行.

现在,如果我们执行sometest.php,我们将获得:

include_once 'debug.php';
 called in sometest.php on line 5
$a = 'foo';
 called in sometest.php on line 7
$b = 'bar';
 called in sometest.php on line 8
$c = $a . $b;
 called in sometest.php on line 9
$d = $e = "hello";
 called in sometest.php on line 10
strlen($d);
 called in sometest.php on line 11
$hello = 'world';
 called in somefile.php on line 3
include 'somefile.php';
 called in sometest.php on line 13
Run Code Online (Sandbox Code Playgroud)

您可以看到somefile.php包含在最后,即使它之前被调用过$hello = 'world'.这是因为当包含完成该行时,将调用tick函数,而不是在它开始时.

此外,在函数/方法声明中调用tick函数:

<?php

function foo() {
    return 'bar';
}

foo();
Run Code Online (Sandbox Code Playgroud)

会给你这样的东西:

}
 called in somefunc.php on line 5   # this is the function declaration
foo();
 called in somefunc.php on line 7   # this is the function call
Run Code Online (Sandbox Code Playgroud)

注意:使用ticks时要小心,因为在5.3.0之前,线程Web服务器不支持它.