difference between call by value and call by reference in php and also $$ means?

后端 未结 5 1179
说谎
说谎 2021-01-05 07:00

(1) I want to know what is the difference between call by value and call by reference in php. PHP works on call by value or call by reference?

(2) And a

5条回答
  •  攒了一身酷
    2021-01-05 07:56

    Let's define a function:

    function f($a) {
      $a++;
      echo "inside function: " . $a;
    }
    

    Now let's try calling it by value(normally we do this):

    $x = 1;
    f($x);
    echo "outside function: " . $x;
    
    //inside function: 2
    //outside function: 1
    

    Now let's re-define the function to pass variable by reference:

    function f(&$a) {
      $a++;
      echo "inside function: " . $a;
    }
    

    and calling it again.

    $x = 1;
    f($x);
    echo "outside function: " . $x;
    
    //inside function: 2
    //outside function: 2
    

    You can pass a variable by reference to a function so the function can modify the variable. More info here.

提交回复
热议问题