How to catch any method call on object in PHP?

前端 未结 3 577
予麋鹿
予麋鹿 2020-12-03 02:38

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

3条回答
  •  一整个雨季
    2020-12-03 03:09

    Taking your original Foo implementation you could wrap a decorator around it like this:

    class Foo 
    {
        public function bar() {
            echo 'foobar';
        }
    }
    
    class Decorator 
    {
        protected $foo;
    
        public function __construct(Foo $foo) {
           $this->foo = $foo;
        }
    
        public function __call($method_name, $args) {
           echo 'Calling method ',$method_name,'
    '; return call_user_func_array(array($this->foo, $method_name), $args); } } $foo = new Decorator(new Foo()); $foo->bar();

提交回复
热议问题