你可以使用debug_backtrace
,有点像这样:
顺便说一句,看看手册页面上的评论:有一些有用的功能和建议;-)
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();
将输出:var_dump
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
和 :echo
called by Foo :: __construct
但是,尽管它看起来不错,但我不确定它是否应该在您的应用程序中用作“正常的东西”......实际上似乎很奇怪:在我看来,有了一个好的设计,一种方法就不需要知道它叫什么。