如何捕获PHP中对象的任何方法调用? [英] How to catch any method call on object in PHP?
本文介绍了如何捕获PHP中对象的任何方法调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图弄清楚如何捕获PHP对象中调用的任何方法.我知道魔术函数__call
,但是它仅对被调用对象上不存在的方法才触发.
I am trying to figure out how to catch any method called on an object in PHP. I know about the magic function __call
, but it is triggered only for methods that do not exist on the called object.
例如,我有这样的东西:
For example i have something like this:
class Foo
{
public function bar()
{
echo 'foobar';
}
public function override($method_name,$method_args)
{
echo 'Calling method ',$method_name,'<br />';
$this->$method_name($method_args); //dirty, but working
}
}
当我这样做时:
$foo = new Foo();
$foo->bar();
我想要这个输出:
Calling method bar
foobar
代替这个:
foobar
有什么办法可以做到这一点?请帮助:)
Is there any way how to do this? Help please :)
推荐答案
采用原始的Foo
实现,您可以将decorator
包裹在其周围,如下所示:
Taking your original Foo
implementation you could wrap a decorator
around it like this:
class Foo
{
public function bar() {
echo 'foobar';
}
}
class Decorator
{
protected $foo;
public function __construct(Foo $foo) {
$this->foo = $foo;
}
public function __call($method_name, $args) {
echo 'Calling method ',$method_name,'<br />';
return call_user_func_array(array($this->foo, $method_name), $args);
}
}
$foo = new Decorator(new Foo());
$foo->bar();
这篇关于如何捕获PHP中对象的任何方法调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文