search

Home  >  Q&A  >  body text

php - What impact will the ampersand reference pass have on the operation results?

$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中文网2721 days ago718

reply all(3)I'll reply

  • typecho

    typecho2017-06-21 10:12:41

    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

    reply
    0
  • phpcn_u1582

    phpcn_u15822017-06-21 10:12:41

    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...

    reply
    0
  • 学习ing

    学习ing2017-06-21 10:12:41

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

    reply
    0
  • Cancelreply