如何创建每次调用公共方法都被调用的方法?

编程入门 行业动态 更新时间:2024-10-15 16:23:37
本文介绍了如何创建每次调用公共方法都被调用的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我如何创建一个在每次调用公共方法时都会被调用的方法?您也可以说这是方法调用后的钩子.

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();

更多推荐

如何创建每次调用公共方法都被调用的方法?

本文发布于:2023-11-25 02:19:05,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1627924.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:方法

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!