Pass by value and pass by reference in php

The value transfer in php, when the variable value is modified, the original value will not be changed, but if it is passed by reference, the original value will be changed. Here are a few examples:

1. String type

function main(){
    $str = "abc";
    change($str);
    var_dump ($ str);
}
function change($str){
    $str = "def";
}
main();
The result is, abc, no change

If pass by value

function main(){
    $str = "abc";
    change($str);
    var_dump ($ str);
}
function change(&$str){
    $str = "def";
}
main();
The result is def, changed


2. Array type

function main(){
    $arr = array("aaa","bbb");
    swap($arr);
    var_dump($arr);
}

function swap($str){
    $ temp = $ str [0];
    $ str [0] = $ str [1];
    $ str [1] = $ temp;
}
main();
In this way, the result is unchanged, or the original value. This is a bit confusing. It is reasonable to say that the array passed should be the address. In fact, it is not. It is still a value, which is still different from java.


After changing to pass by reference

function main(){
    $arr = array("aaa","bbb");
    swap($arr);
    var_dump($arr);
}

function swap(&$str){
    $ temp = $ str [0];
    $ str [0] = $ str [1];
    $ str [1] = $ temp;
}
main();
the result has changed


3. What about the object type, let's take a look

class Car{
    public $color = "red";
}

function main(){
    $car = new Car();
    echo $car->color."<br>";//Before changing
    change($car);
    echo $car->color;//After changing
}
main();
function change($car){
    $car->color = "white";
}

The result is that red and white have changed, which means that when the object type is passed, it is passed by reference.





Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325939066&siteId=291194637