How can I create a method that gets called every t

2019-06-24 17:08发布

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.

My current code:

<?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

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";
}

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.

标签: php oop
1条回答
Lonely孤独者°
2楼-- · 2019-06-24 17:37

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();
查看更多
登录 后发表回答