21

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?

Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
omg
  • 130,444
  • 137
  • 283
  • 343

3 Answers3

20

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);

karim79
  • 334,458
  • 66
  • 409
  • 405
  • have a look at https://blog.penjee.com/passing-by-value-vs-by-reference-java-graphical/ for conceptual understanding. – shellbot97 Feb 17 '21 at 17:19
  • I understand the question that this is known, the question is, why would you use & when calling a function (not when defining a function)? – Thorsten Staerk Jan 02 '22 at 16:22
-3

It's a pass-by-reference.

​​​​​

Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
PaulJWilliams
  • 18,549
  • 3
  • 49
  • 78
  • 2
    Am I right in thinking it no longer applies from PHP 5 onwards? – Ian Oxley Jun 17 '09 at 12:24
  • I know it mean pass-by-reference when defining functions,but is it when calling a function? – omg Jun 17 '09 at 12:25
  • @Ian: Partly. Objects are always passed by reference, whereas anything else is copied. It does not make any sense with $this, but might be useful for large array, for example. – soulmerge Jun 17 '09 at 12:38
-3
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
flik
  • 3,135
  • 2
  • 17
  • 29