php - How can I create a method that gets called every time a public method gets called? -


how can create method gets called every time public method gets called? post-method-call-hook.

my current code:

<?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(); 

the current output in code be:

foo called bar called 

i baz() method called every time public method gets called. e.g.

baz called foo called baz called bar called 

i know have done this:

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

but wouldn't solve problem because that's not orthogonal , it's relatively painful implement if i'd have 100 methods need have other method called before them.

might not expect or want exactly, using magic method __call , marking public methods protected or private can 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(); 

Comments

Popular posts from this blog

javascript - backbone.js Collection.add() doesn't `construct` (`initialize`) an object -

php - Get uncommon values from two or more arrays -

Adding duplicate array rows in Php -