How to catch any method call on object in PHP?
Asked Answered
W

3

33

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 do not exist on the called object.

For example i have something like this:

class Foo
{
  public function bar()
  {
    echo 'foobar';
  }

  public function override($method_name,$method_args)
  {
    echo 'Calling method ',$method_name,'<br />';
    $this->$method_name($method_args); //dirty, but working
  }
}

And when i do this:

$foo = new Foo();
$foo->bar();

I want this output:

Calling method bar
foobar

instead of this one:

foobar

Is there any way how to do this? Help please :)

Wheatley answered 13/7, 2010 at 22:8 Comment(0)
M
51

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();
Marzipan answered 13/7, 2010 at 22:26 Comment(1)
One case where this won't work is if you have methods that expect Foo, eg someMethod(Foo $foo)Corbin
G
2

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.

Gal answered 13/7, 2010 at 22:12 Comment(1)
Can you be more specific please? Just a small example :)Wheatley
A
2

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
   }
}
Anatomist answered 10/5, 2018 at 16:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.