What does “&” mean here in PHP?

后端 未结 3 1577
情书的邮戳
情书的邮戳 2020-12-07 00:47

Consider this PHP code:

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

I know it means pass-by-reference when defining function

相关标签:
3条回答
  • 2020-12-07 01:04

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

    0 讨论(0)
  • 2020-12-07 01:14

    It's a pass-by-reference.

    ​​​​​

    0 讨论(0)
  • 2020-12-07 01:14
    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
    
    0 讨论(0)
提交回复
热议问题