-1

我有以下代码:

function abcdef() { }

function test($callback) {
    // I need the function name string("abcdef") here?
}

test(abcdef);

是否可以在测试函数中获取函数名称?那么匿名函数呢?

4

2 回答 2

2

之前有人问过这个问题:如何在 PHP 中获取被调用者?

您可以使用debug_backtace获得所需的信息。这是我发现的一个非常干净的功能:

<?php
/**
 * Gets the caller of the function where this function is called from
 * @param string what to return? (Leave empty to get all, or specify: "class", "function", "line", "class", etc.) - options see: http://php.net/manual/en/function.debug-backtrace.php
 */
function get_caller($what = NULL)
{
    $trace = debug_backtrace();
    $previousCall = $trace[2]; // 0 is this call, 1 is call in previous function, 2 is caller of that function

    if(isset($what)) {
        return $previousCall[$what];
    } else {
        return $previousCall;
    }   
}

你(可能)像这样使用它:

<?php
function foo($full)
{
    if ($full) {
        return var_export(get_caller(), true);
    } else {
        return 'foo called from ' . get_caller('function') . PHP_EOL;
    }
}

function bar($full = false)
{
    return foo($full);
}

echo bar();
echo PHP_EOL;
echo bar(true);

返回:

foo called from bar

array (
  'file' => '/var/www/sentinel/caller.php',
  'line' => 31,
  'function' => 'bar',
  'args' =>
  array (
    0 => true,
  ),
)
于 2013-07-26T15:59:31.423 回答
-2

您可以尝试使用 function.name :

function abcdef() { }

function test($callback) {
    alert($callback.name)
}

test(abcdef);
于 2013-07-26T15:33:34.427 回答