1

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.

1
  • 1
    why? sounds like poor design if this is needed. Commented Feb 26, 2012 at 23:54

2 Answers 2

2

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.
Sign up to request clarification or add additional context in comments.

3 Comments

The problem is that I want this function to be called on existing methods
You can't intercept a method call if it's already accessible in PHP. There's a lot of design patterns and techniques that make this possible and manageable but it all starts by making the method inaccessible in one way or another. You can get into something like $myClass->callMethod('methodName', array('args')) but that seems like a very poor solution
Nice. So I'll make me methods inaccessible (I 'll find the best way for that. I have 2-3 different ways in my mind) and I will use call. Nice. Thank you very much :-)
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.