How to catch any method call on object in PHP?

前端 未结 3 567
予麋鹿
予麋鹿 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,'<br />';
           return call_user_func_array(array($this->foo, $method_name), $args);
        }
    }
    
    $foo = new Decorator(new Foo());
    $foo->bar();
    
    0 讨论(0)
  • 2020-12-03 03:22

    You can wrap an object around the object, intercepting any calls then forwarding them on the original object and returning the result.

    Just store the object as a variable in your wrapper class and use overloading methods in your wrapper class to call/set/get/check on the object.

    $object = new AnyObject;
    $object = new Wrapper($object);
    
    $object->anyMethod();
    $object->anyVar = 'test';
    echo $object->anyVar;
    echo $object['array form'];
    

    Looping the wrapper class in foreach is probably harder. Havent tried that.

    0 讨论(0)
  • 2020-12-03 03:36

    If you set the function to private , call will trap any call to it from the outside will be trapped in __call, but you can call it from the inside

    class Foo
    {
       private function bar()
       {
          echo 'foobar';
       }
    
       public function __call($method_name,$method_args)
       {
          echo 'Calling method ',$method_name,'<br />';
          $this->$method_name(); //dirty, but working
       }
    }
    
    0 讨论(0)
提交回复
热议问题