Reputation: 9076
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;
}
}
Upvotes: 0
Views: 1894
Reputation: 1732
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;
}
?>
Upvotes: 0