Are multiple variable assignments done by value or reference?

后端 未结 7 2132
天命终不由人
天命终不由人 2020-12-10 00:33
$a = $b = 0;

In the above code, are both $a and $b assigned the value of 0, or is $a just refer

7条回答
  •  执笔经年
    2020-12-10 01:11

    It depends what're you assigning.

    If you're assigning a value, then the assignment copies the original variable to the new one.

    Example 1:

    $a = $b = 0;
    $b++; echo $a;
    

    Above code will return 0 as it's assignment by value.

    Example 2:

    $a = ($b = 4) + 5; // $a is equal to 9 now, and $b has been set to 4.
    

    An exception to the usual assignment by value behaviour within PHP occurs with objects, which are assigned by reference in PHP 5 automatically. Objects may be explicitly copied via the clone keyword.

    Example 3

    $a = $b = $c = new DOMdocument();
    $c->appendChild($c->createElement('html'));
    echo $a->saveHTML();
    

    Above code will print .

提交回复
热议问题