Nehal Hasnayeen
Nehal Hasnayeen

Reputation: 1223

why pass-by-reference doesn't change the value of a variable?

$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

Answers (4)

Shai
Shai

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

Adam Sinclair
Adam Sinclair

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

Bartosz Polak
Bartosz Polak

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

srikant
srikant

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

Related Questions