How to create a method that is called every time a public method is called?

How to create a method that is called every time a public method is called? You can also say that this is a method call after the call.

My current code is:

<?php class Name { public function foo() { echo "Foo called\n"; } public function bar() { echo "Bar called\n"; } protected function baz() { echo "Baz called\n"; } } $name = new Name(); $name->foo(); $name->bar(); 

Current output in this code:

 Foo called Bar called 

I would like the baz () method to be called every time another public method is called. For instance.

 Baz called Foo called Baz called Bar called 

I know I could do something like this:

 public function foo() { $this->baz(); echo "Foo called\n"; } 

But that would not solve my problem, because it was not orthogonal, and it was relatively painful to implement if I had 100 methods that should have called this other method in front of them.

+4
source share
1 answer

It may not be what you expect or want exactly, but using the magic __call method and marking protected or closed public methods, you can get the desired effect:

 <?php class Name { public function __call($method, $params) { if(!in_array($method, array('foo', 'bar'))) return; $this->baz(); return call_user_func_array( array($this, $method), $params); } protected function foo() { echo "Foo called\n"; } protected function bar() { echo "Bar called\n"; } protected function baz() { echo "Baz called\n"; } } $name = new Name(); $name->foo(); $name->bar(); 
+2
source

All Articles