I have a function that is often called inside of other functions, and I'd like to be able to find out automatically what the name of the referring function (if any) was.
Something like this:
function do_something()
{
do_something_else();
}
function do_something_else()
{
echo referring_function(); // prints 'do_something'
}
Is there any easy way to do this? Note that I know it can be done manually by passing the name as a parameter, but I'd like to know if there's a simpler approach to this. Also, I'm not looking for the __FUNCTION__
constant, as that returns the name of the function in which it is called. I want the name of the function that called the current function.
You can use the magic constants __METHOD__ (includes the class name) or __FUNCTION__ (just function name) depending on if it's a method or a function... =) METHOD includes the class name, FUNCTION is just that. The latter is equally available in the method of a class.
PHP Function Arguments Information can be passed to functions through arguments. An argument is just like a variable. Arguments are specified after the function name, inside the parentheses. You can add as many arguments as you want, just separate them with a comma.
To create an instance of a class, the new keyword must be used. An object will always be created unless the object has a constructor defined that throws an exception on error. Classes should be defined before instantiation (and in some cases this is a requirement).
You could abuse debug_backtrace()
horribly to do this. Seems like there should be a better way... but I'm not thinking of it.
It seems kind of weird that you'd want to do this. If you have a real need for a function to know who is calling it, you probably have a design problem.
However, if you're sure you want to do it, you could just define a little global function like this:
function callerId(){
$trace = debug_backtrace();
return $trace[2]['function'];
}
That will always return the name of the function that called the function that called it. Unless, of course, the function that calls callerId()
was called from the top-level script.
So, a usage example:
function callerId(){
$trace = debug_backtrace();
return $trace[2]['function'];
}
function do_something(){
do_something_else();
}
function do_something_else(){
$who_called = callerId();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With