ds111 Posted December 22, 2009 Share Posted December 22, 2009 Hello! I have the following code, for example: class Controller_test extends controller_template { function action_index() { $this->execute_hooks("action_index"); } } My execute_hooks function is this: if ( isset ( $this->hooks[$where] ) ) { if (is_array($this->hooks[$where])) { foreach($this->hooks[$where] as $key => $value) { $file = $value['file']; $function = $value['function']; require ( $file ); $function() } } } This works correctly, however...I want something a bit more... I want it to literally **add code to the function** See the require( $file ); line? Here's an example of a file: <?php function test() { echo "Hi!"; } ?> it calls the test() function, and echos "hi" in the correct place... But what If I want to use some class-specific variable? It doesn't work. I tried to literally read the file contents then return it to the execute_hooks() call, but that doesn't work. So basically I want to turn this: <?php $this->execute_hooks("test"); ?> to this: <?php echo "hi!"; ?> How do i do it? Quote Link to comment https://forums.phpfreaks.com/topic/186059-a-hook-system-question/ Share on other sites More sharing options...
laffin Posted December 23, 2009 Share Posted December 23, 2009 Just a thought, would ya need an empty function set first? $function_code=null than add the extra code to the function $function_code.='echo "hello";'; than just continue adding more code as neccessary. $function_code.='echo " world";'; than just create an anonymous function, $func=create_function('',$a); now the anonymous function can be called anytime with $func(); but if ya want to, I suppose ya can bypass the creation of functions entirely, and use eval instead if you want an immediate return Quote Link to comment https://forums.phpfreaks.com/topic/186059-a-hook-system-question/#findComment-983057 Share on other sites More sharing options...
ignace Posted December 23, 2009 Share Posted December 23, 2009 In order to access object variables you need to pass the object reference ($this) to your function/object. protected function _executeHooks($identifier) { if ($hooks = $this->_getRegisteredHooks($identifier) && $hooks->count()) { foreach ($hooks as $hook) { try { $this->_executeHook($hook); } catch(Exception $e) {/* In case an invalid hook would make it to the hooks ArrayObject */} } } } protected function _executeHook(Hook $hook) { $hook->execut($this); } protected function _getRegisteredHooks($identifier) { return $this->_hooks->offsetExists($identifier) ? $this->_hooks->offsetGet($identifier) : new ArrayObject(/* NullObject */); } This is ofcourse just an example and may differ depening on your OO design Quote Link to comment https://forums.phpfreaks.com/topic/186059-a-hook-system-question/#findComment-983161 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.