PHP,反正知道什么方法/类叫另一个?

时间:2010-11-02 16:38:29

标签: php oop

  

可能重复:
  Caller function in PHP 5?

我有一些彼此扩展的对象,并调用各种辅助方法。我想知道是否有办法检测哪个方法称为另一个。这是一个例子:

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();

1 个答案:

答案 0 :(得分:2)

您可以像这样使用debug_backtrace

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();
   }
}

您可以使用var_dump检查输出:

$trace = debug_backtrace();
var_dump($trace);