Reputation: 2184
I have a function that takes a variable number of parameters, and I have to pass them by reference to another function.
Such as
function my_function($arg0, $arg1, $arg2, ...)
{
my_other_function(&$arg0, &$arg1, &$arg2, ...);
}
So that when I pass things by reference to my_function
, my_other_function
also gets them by reference.
Is there a way to do this?
Upvotes: 0
Views: 122
Reputation: 197795
Technically you are not doing this:
function my_function($arg0, $arg1, $arg2, ...)
{
my_other_function(&$arg0, &$arg1, &$arg2, ...);
}
but this:
function my_function(&$arg0, &$arg1, &$arg2, ...)
{
my_other_function($arg0, $arg1, $arg2, ...);
}
However as @johannes already wrote, there is no good support for variable number of arguments that are references in PHP (and who could know better). func_get_args
Docs for example does not work with references.
Instead make use of the suggestion to pass all references via an array parameter. That works.
function my_function(array $args)
{
my_other_function($args);
}
Upvotes: 1
Reputation: 15969
I wonder why you need this. In general references are bad in PHP.
If you really want to do this the only proper way (ignoring call-time pass-by-ref hacks, which won't work with PHP 5.4 anymore anyways) is to use an array wrapping the parameters:
function myfunc(array $data) {
$data[0] += 42;
/* ... */
}
$var = 0;
myfunc(array(&$var /*, ... */));
echo $var; // prints 42
For passing to the other function you can then use call_user_func_array()
Upvotes: 3