1

I have:

function increment(&$var)
{
    $var++;
}

$a = 0;
call_user_func('increment', $a);
echo $a."\n";

Why does this return:

Warning: Parameter 1 to increment() expected to be a reference, value given in

and $a is still 0. Why is this?

Any references to official documentation would help.

1

2 Answers 2

2

Documentation says "Note: Note that the parameters for call_user_func() are not passed by reference."

You might use call_user_func_array instead.

function increment(&$a) {
    $a++;
}

$x = 1;

call_user_func_array("increment", array(&$x));

echo $x;
1

From the documentation of call_user_func:

Calls the callback given by the first parameter and passes the remaining parameters as arguments.

This is what you want using call_user_func_array instead of call_user_func:

<?php
function increment(&$var)
{
    $var++;
}

$a = 0;
call_user_func_array("increment", array(&$a));
echo $a."\n";

Not the answer you're looking for? Browse other questions tagged or ask your own question.