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