1

Possible Duplicate:
Caller function in PHP 5?

Like this:

function foo(){
  do_something();
}

function do_something(){
  // How can I find out if this function was called from "foo" ?
}

Is this possible in PHP?

(Note that in my case the do_something() function is actually a class method)

Community
  • 1
  • 1
Alex
  • 66,732
  • 177
  • 439
  • 641
  • 1
    I'll just throw this out, know it isn't what you are looking for, but why not just pass it in as an argument? – Jess Jun 28 '11 at 05:19
  • See: http://stackoverflow.com/questions/190421/caller-function-in-php-5 – Ozair Kafray Jun 28 '11 at 05:20
  • it's kind of complicated... But in essence I don't have any control over the foo() function. That function only accepts a callback as argument – Alex Jun 28 '11 at 05:20

3 Answers3

4

You want to use debug_backtrace() (manpage)

Florian
  • 3,145
  • 1
  • 27
  • 38
  • 1
    its name sounds scary. Is it OK use that outside of a dev environment? – Alex Jun 28 '11 at 05:24
  • If you really have to use it, you can use it. But don't try to change the behaviour of the function depending on the caller function but on the arguments (i know there are situations where it's necessary to get the caller function) – Florian Jun 28 '11 at 05:26
4

You can use debug_backtrace, which will let you access the call stack.

function do_something(){
   $trace = debug_backtrace();
   if($trace[1]['function'] == 'foo'){
      // called from foo
   }
}
Mark Elliot
  • 75,278
  • 22
  • 140
  • 160
3

Have a look at Caller function in PHP 5?

Community
  • 1
  • 1
TheITGuy
  • 722
  • 4
  • 15