如何创建每次调用公共方法都被调用的方法? [英] How can I create a method that gets called every time a public method gets called?

查看:89
本文介绍了如何创建每次调用公共方法都被调用的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

这篇关于如何创建每次调用公共方法都被调用的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆