0

I am not understanding the following example in php.net. can anyone explain ?

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

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

// You can use this instead
call_user_func_array('increment', array(&$a));
echo $a."\n";
?>
What array(&$a) means? what will the intial value of $a?

1 Answers1

0

The docs state that "parameters for call_user_func() are not passed by reference". In the given example

function increment(&$var)
{
    $var++;
}
call_user_func('increment', $a);

the value of $a will not be incremented, PHP will raise a warning Parameter 1 to increment() expected to be a reference, value given instead. Code inside the callabe will not be executed, the result of call_user_func() however is NULL.

You cannot call the funtion with call_user_func('increment', &$a) either, since Call-time pass-by-reference has been removed in PHP 5.4. This is what the example is supposed to demonstrate.

Using call_user_func_array() allows the parameter to be passed as reference, so the result of

$a = 0;
call_user_func_array('increment', array(&$a));

is 1.

To use the callable without a reference, return the value from the function and assign this return value to $a instead:

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

$a = 0;
$a = call_user_func('increment', $a);
print 'a: ' . $a . PHP_EOL;

Result:

a: 1
code-kobold
  • 829
  • 14
  • 18