3

我已经查过了,我知道答案可能涉及使用debug_backtrace(),但我正在努力研究如何使用它或它究竟做了什么。

基本上,如果这是 index.php:

<?php
//some code
//some more code

require "functions.php";

print_line();

//some code

print_line();
?>

和functions.php是:

<?php
function print_line(){
    $line="[line that this function was called at]";
    print "This function was called from line $line of index.php<br />";
}
?>

正确的设置方法是什么,$line以便输出为:

This function was called from line 7 of index.php
This function was called from line 11 of index.php
4

2 回答 2

12

debug_backtrace()包含所有嵌套函数调用,一直到从 0(最接近的)索引的当前范围。

因此,当您需要调用print_line()的行时,只需使用:

<?php
function print_line(){
    $backtrace = debug_backtrace();

    $line=$backtrace[0]['line'];
    print "This function was called from line $line of index.php<br />";
}

或从 PHP 5.4 开始:

$line=debug_backtrace()[0]['line'];
于 2013-08-03T20:59:58.810 回答
0

您可以使用下面的代码来获取当前行,只需将其作为参数传递给您的 print_line() 函数

print_line(__line__);
于 2013-08-03T20:54:11.410 回答