Find out which class called a method in another class

you could use debug_backtrace, a bit like this :

BTW, take a look at the comments on the manual page : there are some useful functions and advices given 😉

class Foo
{
  public function __construct()
  {
    $bar = new Bar();
    $bar->test();
  }
}

class Bar
{
  public function test()
  {
      $trace = debug_backtrace();
      if (isset($trace[1])) {
          // $trace[0] is ourself
          // $trace[1] is our caller
          // and so on...
          var_dump($trace[1]);

          echo "called by {$trace[1]['class']} :: {$trace[1]['function']}";

      }
  }
}
$foo = new Foo();

The var_dump would output :

array
  'file' => string '/home/squale/developpement/tests/temp/temp.php' (length=46)
  'line' => int 29
  'function' => string '__construct' (length=11)
  'class' => string 'Foo' (length=3)
  'object' => 
    object(Foo)[1]
  'type' => string '->' (length=2)
  'args' => 
    array
      empty

and the echo :

called by Foo :: __construct

But, as nice as it might look like, I am not sure it should be used as a “normal thing” in your application… Seems odd, actually : with a good design, a method should not need to know what called it, in my opinion.

Leave a Comment