给一个函数 __LINE__ 变量而不需要声明它

Give a function the __LINE__ variable without needing to declare it

所以我正在尝试创建一个变量 class,这意味着我可以动态命名我的变量。我想在我的代码中加入 undeclared variable at line x。我设法使一个函数像这样被调用:

function ($varname, $line = 0) {
  // Example
  echo 'unknwon variable found at line '.$line;
}

但我希望能够删除函数的 line = 0 ,而不是只给它一行而不需要像这样调用函数:

exampleFunction('Name', __LINE__);

而是这样称呼它:

exampleFunction('Name');

并且 __LINE__ 变量与其一起传递,而不需要包含它。 - 我试着让被调用的函数看起来像这样:

exampleFunction($varname, __LINE__) {
  // Executed code.
}

虽然这也没有成功,但还是报错了。

您可以在 exampleFunction 中使用 debug_backtrace 方法来获取来电信息。

http://php.net/manual/tr/function.debug-backtrace.php

示例(从 php.net 复制)

<?php
// /tmp/a.php dosyası

function a_test($str)
{
    echo "\nHi: $str";
    var_dump(debug_backtrace());
}

a_test('friend');
?>

<?php
// /tmp/b.php dosyası
include_once '/tmp/a.php';
?>

输出:

Hi: friend
array(2) {
[0]=>
array(4) {
    ["file"] => string(10) "/tmp/a.php"
    ["line"] => int(10)
    ["function"] => string(6) "a_test"
    ["args"]=>
    array(1) {
      [0] => &string(6) "friend"
    }
}
[1]=>
array(4) {
    ["file"] => string(10) "/tmp/b.php"
    ["line"] => int(2)
    ["args"] =>
    array(1) {
      [0] => string(10) "/tmp/a.php"
    }
    ["function"] => string(12) "include_once"
  }
}