php - What impact will the ampersand reference pass have on the operation results?
PHP中文网
PHP中文网 2017-06-21 10:10:41
0
3
711

$a = 1;
$b = &$a; //Pass address. Commenting out this line returns 5. If it is not commented out (PHP version <7), it returns 6
$c = ( $a) ( $a);
echo $c;
Does it have anything to do with the version? ? Also, the result is 6, which is really puzzling to me

PHP中文网
PHP中文网

认证高级PHP讲师

reply all(3)
typecho

Let’s first talk about the operation of adding reference assignment

$b = &$a;

For this operation, it can be considered that both $a and $b point to the memory where the original $a variable is located (for convenience of explanation later, it is called memory X), that is to say, any subsequent The operations of $a or $b are directly modifying the value in this memory.

So the running process after adding this line:

  1. The previous steps are omitted, the initial a is 1

  2. $c = (++$a) + (++$a) The two times ++$a are both operating memory twice, so when calculating the value of $c, the value of this memory is taken, that is, the value in memory X after it has been incremented twice. Therefore, it is 3 + 3 = 6 (when calculating $c, the value stored in memory X is 3).

    Let’s talk about the operation after commenting the reference
If no reference is added, then the auto-increment operation of

$a

directly modifies

memory X, and then returns a copy of memory It is not obtained directly from Memory X, but a copy after changing the value of Memory

phpcn_u1582

This is related to the underlying implementation of PHP. It’s a long story. It is recommended to look at the analysis of the same problem on github.
An exploration caused by a PHP bug:
https://github.com/xurenlu/ph...

学习ing

You output C, what does C have to do with your B?

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template