Wednesday, July 8, 2009

call_user_func_array vs $myfunction( &$params )

call_user_func_array vs $myfunction( &$params )

Hi,

I was looking at
http://www.php.net/manual/en/function.call-user-func-array.php and I
was wondering...

Given,
// --
function foo( &$params)
{
echo 'bar';
}
// --

What is the difference between

// --
$params = array( $stuff);
$myFn = 'foo';
$myFn($params)
// --

And

// --
$params = array( $stuff);
$myFn = 'foo';
call_user_func_array( $myFn, $params );
// --

Wont they both achieve the same result?

FFMG
=============================

call_user_func_array is useful when the number of parameters to a called
function is variable or unknown, for example:

function nice_dump() {
$params = func_get_args();
echo "
";
call_user_func_array('var_dump', $params);
echo "
";
}

nice_dump(1, 2, 3);

=============================

Indeed, it's not really function name that's interesting in this
particular example, it's the parameters that particular piece of code
doesn't have to worry about.

Then again, one of it's major advantages is it also supports callbacks, so
you can easily give a class function or object method to it. Your code
would be rather complex to get that otherwise...

No comments: