Passing arguments to callbacks

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

Threaded View
No point re-inventing the wheel, so thought I'd see if  
anybody's got some good example code kicking around.

(Please excuse trivial syntactical errors, it's all coming
off the top of my head).

Say I have a function thus:

function munge($a) {
  return ($a * 2);

Now I extend it with a callback:

function munge($a, $callback = NULL) {
  if ($callback != NULL) {
  return ($a * 2);

function add_two ($in) {
  return ($in + 2);

then I would call munge(3, 'add_two'); to get 10.

Q1.  Is testing callback against NULL a sensible way of implementing an
optional callback?  
Q1a. Should I replace it with an is_callable() or function_exists(), or
augment it with one, and which of these two makes more sense here?  
(I'm guessing replace with is_callable()).

I now want to introduce another callback:

function add_var($in, $var) {
  return ($in + $var);
so that I can call
munge(3, 'add_two');
munge(3, 'add_var', 1);
to get results of 6, 10, and 8 respectively.  

And, of course, I want to have the number of parameters sent to the  
callback to be arbitrary.

So, this line of thought leads me to call_user_func_array();

function munge($a, $callback = NULL, $callback_args = NULL) {
  if is_callable($callback) {
    if is_array($callback_args)  
      call_user_func_array($callback, $callback_args);
  return ($a * 2);

and I call  
munge(3, 'add_var', array(1));
munge(3, 'complicated', array(1,2,3));
where complicated() is a function taking 4 parameters.

Q2. How does that look, PHP people?
Q2A. Would you add another couple of lines with "if isset" to allow the  
use of call_user_func() for callbacks that only take two parameters?

Re: Passing arguments to callbacks

Quoted text here. Click to load it

Yes, null is fine as default value in this case, but I would use isnull()  
instead of a plain compare.

Quoted text here. Click to load it

You don't have to pass an array. PHP implements variable length argument  
lists. Have a look at
and use func_get_args() to retrieve a variable number of arguments. Your  
function could look like this (exceptions need PHP 5):

function munge($a,$callback=NULL)
if (isnull($callback)) return $a*2; // default
if (!is_callable($callback)) throw new Exception('Invalid callback');
$args=(count($args)>2) ? array_slice($args,2) : array();
return call_user_func_array($callback,$args);

Quoted text here. Click to load it

No. Definitely not.

Re: Passing arguments to callbacks

F Laupretre wrote:


Thanks for the feedback.

Quoted text here. Click to load it

Yes, I thought about this but felt that if you are going to do this:

Quoted text here. Click to load it

you might as well just pass an array in anyway.  Not sure now.

Site Timeline