Paris
Paris

Reputation: 6771

php - Execute snippet on method call

I 'd like to know if there is a way to execute a snippet in PHP each time a method is called inside a class. Similar to the way __construct() works, but it should be called on every method call.

Upvotes: 1

Views: 491

Answers (2)

lisachenko
lisachenko

Reputation: 6092

I can suggest you to use aspect-oriented library for your needs. You will be able to create a pointcut for methods (regular expression) and just make an advice (closure) to call before/after or around of each method. You can have a look at my library for this: Go! AOP PHP

Upvotes: 0

Mike B
Mike B

Reputation: 32155

You're probably looking for __call(). It will be invoked whenever a non-accesible method is invoked.

class MyClass {
  protected function doStuff() {
    echo "doing stuff.";
  }

  public function __call($methodName, $params) {
    echo "In before method.";
    return $this->doStuff();
  }
}

$class = new MyClass();
$class->doStuff(); // In before method.doing stuff.

Upvotes: 2

Related Questions