Pass arguments from a function to another function
I have something like this
function f1($name = ''){
f2("prefix_{$name}", $args);
}
the f1() function is called like:
f1('name', $var1, $var2, $开发者_运维知识库var3);
How can I pass these variables to f2() inside it, the same way they are passed to f1() ?
so instead of f2("prefix_{$name}", $args);
it should be like f2("prefix_{$name}", $var1, $var2, $var3);
Not that I have no control over the f2 function :(
function f1( $name = '' )
{
// get all arguments to this function
$args = func_get_args();
// prefix the first arguments with some prefix
$args[ 0 ] = 'prefix_' . $name;
// call the second function with the $args array as its arguments
call_user_func_array( 'f2', $args );
}
edit:
replaced
$args[ 0 ] = 'prefix_' . $args[ 0 ];
with
$args[ 0 ] = 'prefix_' . $name;
to account for what Gerry said in his answer.
The regular func_get_args() will not take into account any default arguments, so you will need to do something like this:
function func_get_default_args($a) {
$args = array_slice(func_get_args(), 1);
return array_merge($args, array_slice($a, sizeof($args)));
}
function f1($name = ''){
call_user_func_array('f2', func_get_default_args(func_get_args(), $name));
}
精彩评论