23

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,738
  • 21
  • 105
  • 131
omg
  • 136,412
  • 142
  • 288
  • 348

3 Answers3

21

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
  • 339,989
  • 67
  • 413
  • 406
  • 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,738
  • 21
  • 105
  • 131
pauljwilliams
  • 19,079
  • 3
  • 51
  • 79
  • 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,433
  • 2
  • 20
  • 30