-1

I have the following code:

function abcdef() { }

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

test(abcdef);

Is it possible to get the function name within the test function? And what about anonymous functions?

  • Why not just pass a string to the function? – Andre Backlund Jul 26 '13 at 15:35
  • 1
    With PHP 5.3+ anonymous functions are available : http://www.php.net/manual/en/functions.anonymous.php – piddl0r Jul 26 '13 at 15:37
  • Your code will throw a syntax error. You should be passing `abcdef` as a string (`test('abcdef');`). Then you can `echo $callback;`. When you want to call it do, `$callback();`. – gen_Eric Jul 26 '13 at 15:57

2 Answers2

2

This has been asked before: How can I get the callee in PHP?

You can get the information you need with debug_backtace. Here is a very clean function 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;
    }   
}

And you (might) use it like this:

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

Which returns:

foo called from bar

array (
  'file' => '/var/www/sentinel/caller.php',
  'line' => 31,
  'function' => 'bar',
  'args' =>
  array (
    0 => true,
  ),
)
Community
  • 1
  • 1
Brian
  • 541
  • 3
  • 15
  • 1
    Note that `debug_backtrace()` is considered very slow and not ideal for production. – Madara's Ghost Jul 26 '13 at 16:06
  • It's true that it's very slow, but this type of inspection can be useful. Computers are also always getting faster, and this will surely not be considered slow later on. – Brian Jul 02 '14 at 00:06
  • The point isn't how fast computers are. It's how slow it is compared to other things PHP does. It is, and always will be, very slow and not ideal for production. – Madara's Ghost Jul 02 '14 at 06:49
  • You may be right here. But if a developer designs a website that actually needs this maybe they deserve to have it run slow. – Brian Jul 03 '14 at 15:12
-2

You can try with function.name :

function abcdef() { }

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

test(abcdef);
PaoloCargnin
  • 442
  • 2
  • 10