Do I need to use the ampersand in PHP 5.5.X and above anymore?

后端 未结 3 1145
误落风尘
误落风尘 2021-02-15 11:36

I\'m getting mixed signals all over the place.

Do I use the ampersand to pass variables by reference or not?

The following link seems to tell me that it is depre

3条回答
  •  情书的邮戳
    2021-02-15 12:34

    No, it is not.

    • Objects are always automatically passed as references (info! see below for additional important information!)

    • Declaring paramters as references must happen at the function definition:

      function test(&$var) {}
      

      Not at the time of calling it:

      // wrong
      $var = '123';
      test(&$var);
      


    If you pass an object as usual, you can alter the object's state (properties).
    Assume that $obj is an instance of the class TestClass which contains a member variable called hello (click here for a full sample at Ideone.com):

    function modify($obj) { $obj->hello = 'world (modified)!'; }
    
    $obj->hello = 'world';
    modify($obj);
    var_dump($obj->hello);  // outputs "world (modified!)"
    

    This should be self-explanatory. Now, using the same code but assigning another value to $obj instead modifying the object's state results in no modification (→ Ideone.com):

    function modify($obj) { $obj = 42; }
    // ...
    var_dump($obj->hello);  // outputs "world"
    

    Only accepting the parameter explicitly as a reference gives us the ability to completely change the variable's contents (→ Ideone.com):

    function modify(&$obj) { $obj = 42; }
    // ...
    var_dump($obj);         // outputs "42"
    

提交回复
热议问题