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

I have a function that is often called inside other functions, and I would like to know how the name of the referenced function was specified (if any).

Something like that:

function do_something() { do_something_else(); } function do_something_else() { echo referring_function(); // prints 'do_something' } 

Is there an easy way to do this? Please note that I know that this can be done manually by passing the name as a parameter, but I would like to know if there is a simpler approach to this. Also, I'm not looking for the __FUNCTION__ constant, as it returns the name of the function in which it is called. I want the function name to call the current function.

+4
source share
3 answers

You can severely abuse debug_backtrace() to do this. It seems like there should be a better way ... but I don't think about it.

It seems strange that you want to do this. If you have a real need for a function to know who calls it, you probably have a design problem.

However, if you are sure you want to do this, you can simply define a small global function like this:

 function callerId(){ $trace = debug_backtrace(); return $trace[2]['function']; } 

This will always return the name of the function that calls the function it calls. Unless, of course, the function calling callerId() was called from a top-level script.

So, an example of use:

 function callerId(){ $trace = debug_backtrace(); return $trace[2]['function']; } function do_something(){ do_something_else(); } function do_something_else(){ $who_called = callerId(); } 
+10
source

It is possible to make the calling function print its name into one of the function arguments. Sort of:

 function do_something() { do_something_else(__FUNCTION__); } function do_something_else($calling) { echo $calling; // prints 'do_something' } 

Unconfirmed.

0
source
 function callerId(){ $trace = debug_backtrace(); return $trace[2]['function']; } 

It works correctly even if it is used inside any class, but there it is limited to the class. It does not go beyond the class - more than one level (for example, if you use it inside a function that prepares an exception, it will only call the function where it is called).

And here is a slight improvement for this function, which automatically gets the top level - if it is equal to zero or ten (but, on the other hand, who created such a design that would have so many levels).

 protected function Get_CallerFunctionName() { $Function = debug_backtrace(); $Level = count($Function)-1; return $Function[$Level]['function']; } 
0
source