Reply to Passing arguments to callbacks

Your name:

Reply:


Posted by Mary Pegg on 10/03/06 11:45

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) {
$callback($a);
}
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);
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);
else
$callback($a);
}
return ($a * 2);
}

and I call
munge(3, 'add_var', array(1));
and
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?

[Back to original message]


Удаленная работа для программистов  •  Как заработать на Google AdSense  •  England, UK  •  статьи на английском  •  PHP MySQL CMS Apache Oscommerce  •  Online Business Knowledge Base  •  DVD MP3 AVI MP4 players codecs conversion help
Home  •  Search  •  Site Map  •  Set as Homepage  •  Add to Favourites

Copyright © 2005-2006 Powered by Custom PHP Programming

Сайт изготовлен в Студии Валентина Петручека
изготовление и поддержка веб-сайтов, разработка программного обеспечения, поисковая оптимизация