我如何创建一个在每次调用公共方法时都会被调用的方法?您也可以说这是方法调用后的钩子.
How can I create a method that gets called every time a public method gets called? You could also say that this is a post-method-call-hook.
我当前的代码:
<?php class Name { public function foo() { echo "Foo called\n"; } public function bar() { echo "Bar called\n"; } protected function baz() { echo "Baz called\n"; } } $name = new Name(); $name->foo(); $name->bar();此代码中的当前输出为:
The current output in this code would be:
Foo called Bar called我希望每次调用另一个公共方法时都调用baz()方法.例如
I would like the baz() method to get called every time another public method gets called. E.g.
Baz called Foo called Baz called Bar called我知道我可以做这样的事情:
I know that I could have done something like this:
public function foo() { $this->baz(); echo "Foo called\n"; }但这并不能真正解决我的问题,因为那不是真正的正交,如果我有100个需要在其之前调用其他方法的方法,则实现起来会比较痛苦.
But that wouldn't really solve my problem because that's not really orthogonal and it's relatively painful to implement if I'd have 100 methods that need to have this other method called before them.
推荐答案可能不完全是您期望或想要的,但是通过使用魔术方法__call并将这些公共方法标记为受保护或私有,您可以获得预期的效果:
Might not be what you expect or want exactly, but by using the magic method __call and marking those public methods protected or private you can get the desired effect:
<?php class Name { public function __call($method, $params) { if(!in_array($method, array('foo', 'bar'))) return; $this->baz(); return call_user_func_array( array($this, $method), $params); } protected function foo() { echo "Foo called\n"; } protected function bar() { echo "Bar called\n"; } protected function baz() { echo "Baz called\n"; } } $name = new Name(); $name->foo(); $name->bar();更多推荐
如何创建每次调用公共方法都被调用的方法?
发布评论