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;
    }
}
2

2 Answers 2

1

Have a look at the output of debug_backtrace().

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.