获取函数被调用的行?

时间:2013-08-03 20:52:26

标签: php function line call

我看了这个,我知道答案可能涉及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

2 个答案:

答案 0 :(得分:9)

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'];

答案 1 :(得分:0)

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

print_line(__line__);