How to catch any method call on object in PHP?

半腔热情 提交于 2019-11-28 21:10:51
ChristopheD

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

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.

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
   }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!