Get name of caller function in PHP?

Solution 1:

See debug_backtrace - this can trace your call stack all the way to the top.

Here's how you'd get your caller:

$trace = debug_backtrace();
$caller = $trace[1];

echo "Called by {$caller['function']}";
if (isset($caller['class']))
    echo " in {$caller['class']}";

Solution 2:

Xdebug provides some nice functions.

<?php
  Class MyClass
  {
    function __construct(){
        $this->callee();
    }
    function callee() {
        echo sprintf("callee() called @ %s: %s from %s::%s",
            xdebug_call_file(),
            xdebug_call_line(),
            xdebug_call_class(),
            xdebug_call_function()
        );
    }
  }
  $rollDebug = new MyClass();
?>

will return trace

callee() called @ /var/www/xd.php: 16 from MyClass::__construct

To install Xdebug on ubuntu the best way is

sudo aptitude install php5-xdebug

You might need to install php5-dev first

sudo aptitude install php5-dev

more info

Solution 3:

This is very late but I would like to share the function that will give name of the function from which current function is called.

public function getCallingFunctionName($completeTrace=false)
    {
        $trace=debug_backtrace();
        if($completeTrace)
        {
            $str = '';
            foreach($trace as $caller)
            {
                $str .= " -- Called by {$caller['function']}";
                if (isset($caller['class']))
                    $str .= " From Class {$caller['class']}";
            }
        }
        else
        {
            $caller=$trace[2];
            $str = "Called by {$caller['function']}";
            if (isset($caller['class']))
                $str .= " From Class {$caller['class']}";
        }
        return $str;
    }

I hope this will be useful.