2

Possible Duplicate:
Caller function in PHP 5?

I have some objects that extend one another, and calls various helper methods. I am wondering if there is a way to detect which method called another. here's an example:

class Foo {
   function whereAmICalled() {
      $calling_method = '' //would like to get func_caller here when code is executed
      $calling_class = '' //would like to get 'Bar' here when code is executed
   }
}

class Bar extends Foo {
   function func_caller() {
       $this->whereAmIcalled();
   }
}

$bar = New Bar();
$bar->func_caller();
Community
  • 1
  • 1
GSto
  • 41,512
  • 37
  • 133
  • 184
  • Something like debug_backtrace()? I'm not sure to understand what you want to do exactly. – Vincent Savard Nov 02 '10 at 16:40
  • 4
    Duplicate indeed, with the remark that needing this information usually indicates bad design, an almost fundamental OO principle is you shouldn't need nor care which function/class calls the current method. – Wrikken Nov 02 '10 at 16:44
  • If you have to know the caller, then pass this information to the callee instead of letting the callee wade through the debug backtrace – Gordon Nov 02 '10 at 16:46
  • 1
    Unless it's for debugging/tracing purposes, you *really* shouldn't build this into your application. Changing the behaviour of a function based on who called it/where it was called from is a terrible idea. – user229044 Nov 02 '10 at 16:47

1 Answers1

2

You can use debug_backtrace like this:

class Foo {
   function whereAmICalled() {
     $trace = debug_backtrace();
     echo "Caller class: {$trace[1]['class']}, method: {$trace[1]['function']}";
   }
}

class Bar extends Foo {
   function func_caller() {
       $this->whereAmIcalled();
   }
}

You can check the output using var_dump:

$trace = debug_backtrace();
var_dump($trace);
Sarfraz
  • 377,238
  • 77
  • 533
  • 578