0
$string='string';
function change(&$str){
    $str='str';
}
call_user_func('change',$string);
echo $string;

output is 'string'. but $str refer to the $string , so change in $str should also change $string? why the value is still same?

Nehal Hasnayeen
  • 1,203
  • 12
  • 23

4 Answers4

2

http://php.net/manual/en/function.call-user-func.php

It clearly mention that the parameters for call_user_func() are not passed by reference.

srikant
  • 260
  • 3
  • 11
2

It's not possible with call_user_func():

From the PHP documentation:

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

That said you still can use call_user_func_array(). Using the reference becomes now possible. Here's the code you want:

function change(&$str)
{
    $str='str';
}

$string='string';
$parameters = array(&$string);
call_user_func_array('change',$parameters);
echo $string;

However this solution is now Deprecated.

You still can get rid of call_user_func(), and simply do:

function change(&$str)
{
    $str='str';
}

$string='string';
change($string);
echo $string;
Adam Sinclair
  • 1,654
  • 12
  • 15
1

call_user_func doesn't pass by reference. From the PHP docs:

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

(change($string), on the other hand, gives "str" as you would expect).

Further reading: Why does PHP's call_user_func() function not support passing by reference?

Community
  • 1
  • 1
Shai
  • 7,159
  • 3
  • 19
  • 22
1

Here's your error message:

<br />
<b>Warning</b>:  Parameter 1 to change() expected to be a reference, value given on line <b>5</b>   

because call_user_func does not pass parameters by reference.

Try run it like this:

$string='string';
function change(&$str){
    $str='str';
}
change($string);
echo $string;