Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php callback (like jQuery)?

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;
like image 260
kr1zmo Avatar asked Dec 09 '22 10:12

kr1zmo


1 Answers

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
  • Or anonymous functions, with PHP >= 5.3


For a couple examples, take a look at the callback section of the following manual page : Pseudo-types and variables used in this documentation

like image 99
Pascal MARTIN Avatar answered Dec 24 '22 22:12

Pascal MARTIN