我有以下代碼:是否可以通過它的引用來獲取函數的名稱?
function abcdef() { }
function test($callback) {
// I need the function name string("abcdef") here?
}
test(abcdef);
是否有可能得到測試功能中的功能的名稱? 那麼匿名函數呢?
我有以下代碼:是否可以通過它的引用來獲取函數的名稱?
function abcdef() { }
function test($callback) {
// I need the function name string("abcdef") here?
}
test(abcdef);
是否有可能得到測試功能中的功能的名稱? 那麼匿名函數呢?
這已經被問過: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,
),
)
請注意''debug_backtrace()'被認爲非常慢,不適合生產。 –
這確實很慢,但這種檢查類型很有用。電腦也總是變得越來越快,以後肯定不會覺得慢。 – Brian
關鍵不在於電腦的運行速度。它與PHP所做的其他事情相比有多慢。它始終會非常緩慢,並且不適合生產。 –
爲什麼不只是傳遞一個字符串函數? –
使用PHP 5.3以上匿名函數可用:http://www.php.net/manual/en/functions.anonymous.php – piddl0r
您的代碼將引發語法錯誤。您應該將'abcdef'作爲字符串傳遞('test('abcdef');')。然後你可以'echo $ callback;'。當你想調用它的時候,'$ callback();'。 –