是否可以通过它的引用获取函数的名称?

时间:2013-07-26 15:29:38

标签: php callback

我有以下代码:

function abcdef() { }

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

test(abcdef);

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

2 个答案:

答案 0 :(得分:2)

以前曾经问过:How can I get the callee in PHP?

您可以使用debug_backtace获取所需信息。这是一个非常干净的函数I have found

<?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,
  ),
)

答案 1 :(得分:-2)

您可以尝试使用function.name:

function abcdef() { }

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

test(abcdef);