Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get name of caller function in PHP?

Tags:

php

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']}";

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


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.


debug_backtrace() supplies details of parameters, function/method calls in the current call stack.