0

Is there a way to get the name of the calling function in PHP?

In the following code I am using the name of the calling function as part of an event name. I would like to modify the getEventName() function so that it can automatically determine the name of the calling method. Is there a php function that does this?

class foo() {

    public function bar() {
        $eventName = $this->getEventName(__FUNCTION__);
        // ... do something with the event name here 
    }     

    public function baz() {
        $eventName = $this->getEventName(__FUNCTION__);
        // ... do something with the event name here 
    }

    protected function getEventName($functionName) {
        return get_class($this) . '.' . $functionName;
    }
}
DatsunBing
  • 8,684
  • 17
  • 87
  • 172
  • 4
    possible duplicate of [How to get name of calling function/method in PHP?](http://stackoverflow.com/questions/2110732/how-to-get-name-of-calling-function-method-in-php) – Markus Malkusch Oct 27 '14 at 06:28
  • possible duplicate of [Caller function in PHP 5?](http://stackoverflow.com/questions/190421/caller-function-in-php-5) – Gunaseelan Oct 27 '14 at 06:37

2 Answers2

1

Have a look at the output of debug_backtrace().

Markus Malkusch
  • 7,738
  • 2
  • 38
  • 67
0

if you want to know the function that called whatever function you are currently in, you can define something like:

<?php
/**
* Returns the calling function through a backtrace
*/
 function get_calling_function() {
  // a function x has called a function y which called this
  // see stackoverflow.com/questions/190421
  $caller = debug_backtrace();
  $caller = $caller[2];
 $r = $caller['function'] . '()';
 if (isset($caller['class'])) {
$r .= ' in ' . $caller['class'];
}
if (isset($caller['object'])) {
$r .= ' (' . get_class($caller['object']) . ')';
 }
 return $r;
}
?>
munsifali
  • 1,732
  • 2
  • 24
  • 43