25

Consider the following example :

function myTest(&$var)
{ 
    $var++;
    echo "var = {$var}\n";
}

$x = 42;
call_user_func('myTest', $x);

It shows the warning :

Warning: Parameter 1 to myTest() expected to be a reference, value given in /home/alain/workspace/echo/echo.php(57) : eval()'d code on line 7

Note: code written on an online sandbox, explaning the eval.

Any idea how I can pass reference to call_user_func family functions?

0

1 Answer 1

45

I found my answer on the PHP manual :

Note:

Note that the parameters for call_user_func() are not passed by reference.

They also give a trick to do the job :

$x = 42;
call_user_func_array('myTest', array(&$x));
Sign up to request clarification or add additional context in comments.

3 Comments

NO! this is deprecated (pass by referenced is deprecated after php 5.3) !
Hey @T.Todua, this code seems to work on PHP 7. Do you have any link showing this? Cheers. Alain
@T.Todua this actually specifically avoids call-time pass-by-reference by using an array literal or straight variable (no &) rather than something incorrect like call_user_func('myTest', &$x);. The function signature still has to have a reference parameter, and this ensures that the variable the function operates on is still the same variable, rather than a copy made by call_user_func.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.