How to get name of calling function/method in PHP?

You can also use the info provided by a php exception, it's an elegant solution:


function GetCallingMethodName(){
    $e = new Exception();
    $trace = $e->getTrace();
    //position 0 would be the line that called this function so we ignore it
    $last_call = $trace[1];
    print_r($last_call);
}

function firstCall($a, $b){
    theCall($a, $b);
}

function theCall($a, $b){
    GetCallingMethodName();
}

firstCall('lucia', 'php');

And you get this... (voilà!)

Array
(
    [file] => /home/lufigueroa/Desktop/test.php
    [line] => 12
    [function] => theCall
    [args] => Array
        (
            [0] => lucia
            [1] => php
        )

)

The debug_backtrace() function is the only way to know this, if you're lazy it's one more reason you should code the GetCallingMethodName() yourself. Fight the laziness! :D


The simplest way is:

echo debug_backtrace()[1]['function'];

As noted in the comments below, this can be further optimized by passing arguments to:

  • omit both the object and args indices
  • limit the number of stack frames returned
echo debug_backtrace(!DEBUG_BACKTRACE_PROVIDE_OBJECT|DEBUG_BACKTRACE_IGNORE_ARGS,2)[1]['function'];

As of php 5.4 you can use

        $dbt=debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS,2);
        $caller = isset($dbt[1]['function']) ? $dbt[1]['function'] : null;

This will not waste memory as it ignores arguments and returns only the last 2 backtrace stack entries, and will not generate notices as other answers here.