0

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?

2
  • hmmm... func_get_args ? no, it didnot work Commented Jul 21, 2012 at 21:09
  • Yeah, the problem is that if I just use it as is, the passed-by-reference values will get passed by copy to the other function. Commented Jul 21, 2012 at 21:10

2 Answers 2

3

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()

Sign up to request clarification or add additional context in comments.

2 Comments

Great, this worked for me. As for why I'm using it, this is for some meta-programming features in my framework.
Still references seem to e the wrong solution. Maybe wrap stuff that has to be changed in objects? (Remember objects are passed by handle - which mostly feels like passing them by ref)
1

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_argsDocs 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); 
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.