Reputation: 1223
$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?
Upvotes: 0
Views: 74
Reputation: 7317
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?
Upvotes: 1
Reputation: 1649
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;
Upvotes: 2
Reputation: 136
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;
Upvotes: 1
Reputation: 260
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.
Upvotes: 2