找出哪个类别在另一个类别中称为方法 [英] Find out which class called a method in another class
问题描述
PHP中是否有一种方法可以找出另一个对象中称为哪个方法的对象.
Is there a way in PHP to find out what object called what method in another object.
例如:
class Foo
{
public function __construct()
{
$bar = new Bar();
$bar->test();
}
}
class Bar
{
public function test()
{
}
}
$foo = new Foo();
我能找到一种方法是从foo对象中调用测试方法吗?
Would there be a way for me to find out that the test method was called from the foo object?
推荐答案
您可以使用 debug_backtrace
,有点像这样:
顺便说一句,请看一下手册页上的评论:有一些有用的功能和建议;-)
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();
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
但是,尽管看起来不错,但我不确定它是否应该在您的应用程序中用作正常事物" ...似乎有些奇怪,实际上:设计良好的方法不需要知道一种方法在我看来,它叫什么.
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.
这篇关于找出哪个类别在另一个类别中称为方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!