in jQuery you can write something like
$(selector).bind('click', function(e) {
// something was true - do these actions.
});
I was wondering if in php you could do something similar without using eval.
something like this? I know this wont work btw.
class act{
public function bind($pref, $callback) {
if($pref == 'something' ) {
// return and perform actions in $callback?
eval($callback);
}
}
}
Some of you might ask what the need for this is? Well I'm trying to simplify my code without using so many if statements.
$act = new act;
$act->bind('something', function(e) {
echo 'this was the php code to run in the callback';
});
The above code would avoid using a bunch of if statements.
$act = new act;
if( $act->bind('something') ) {
// bind returned true so do this?
}
I know you could use ob_get_contents to return the evaled code, but ewww.
ob_start();
eval('?> ' . $callback . '<?php ');
$evaled = ob_get_contents();
ob_end_clean();
return $evaled;
You can indeed define callback functions (or methods) in PHP.
This can be implemented with either :
call_user_func()
and other functions of its familly
For a couple examples, take a look at the callback section of the following manual page : Pseudo-types and variables used in this documentation
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With