如何捕获 PHP 中对象的任何方法调用?
我试图弄清楚如何捕获 PHP 中对象调用的任何方法。我知道魔术函数__call
,但它仅针对被调用对象上不存在的方法触发。
例如,我有这样的东西:
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
有什么方法可以做到这一点吗?请帮忙:)
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
}
}
And when i do this:
$foo = new Foo();
$foo->bar();
I want this output:
Calling method bar
foobar
instead of this one:
foobar
Is there any way how to do this? Help please :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
采用原始的
Foo
实现,您可以将decorator
包裹在它周围,如下所示:Taking your original
Foo
implementation you could wrap adecorator
around it like this:您可以将对象包装在对象周围,拦截任何调用,然后将它们转发到原始对象并返回结果。
只需将对象作为变量存储在包装类中,并在包装类中使用重载方法来调用/设置/获取/检查该对象。
在 foreach 中循环包装类可能更困难。没试过。
You can wrap an object around the object, intercepting any calls then forwarding them on the original object and returning the result.
Just store the object as a variable in your wrapper class and use overloading methods in your wrapper class to call/set/get/check on the object.
Looping the wrapper class in foreach is probably harder. Havent tried that.
如果将函数设置为 private ,则 call 将捕获任何从外部对其进行的调用将被捕获在 __call 中,但您可以从内部调用它
If you set the function to private , call will trap any call to it from the outside will be trapped in __call, but you can call it from the inside