How to catch any method call on object in PHP?

Viewed 13215

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 :)

3 Answers

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