Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way to get a referring function's name in PHP?

Tags:

function

php

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.

like image 336
Josh Leitzel Avatar asked Sep 15 '09 02:09

Josh Leitzel


People also ask

How to get function name in PHP?

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.

How to pass arguments in PHP?

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.

How to create an instance of a class in PHP?

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).


1 Answers

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();
}
like image 75
timdev Avatar answered Oct 21 '22 22:10

timdev