20
votes

Consider this PHP code:

call_user_func(array(&$this, 'method_name'), $args);

I know it means pass-by-reference when defining functions, but is it when calling a function?

3

3 Answers

19
votes

From the Passing By Reference docs page:

You can pass a variable by reference to a function so the function can modify the variable. The syntax is as follows:

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

$a=5;
foo($a);
// $a is 6 here
?>

...In recent versions of PHP you will get a warning saying that "call-time pass-by-reference" is deprecated when you use & in foo(&$a);

-3
votes

It's a pass-by-reference.

​​​​​

-3
votes
call_user_func(array(&$this, 'method_name'), $args);

This code generating Notice: Notice: Undefined variable: this

Here is a correct example:

<?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";
?>
The above example will output:

0
1