Bug #72173 [Com]: very strange reference behavior (bug?) in PHP 5.6, 7.0
| From: | cf0hay at gmail dot com | Date: | Sat, 07 May 2016 14:25:01 +0000 |
| Subject: | Bug #72173 [Com]: very strange reference behavior (bug?) in PHP 5.6, 7.0 | ||
| References: | 1 | Groups: | php.bugs |
| Request: | Send a blank email to php-bugs+get-200936@lists.php.net to get a copy of this message | ||
Edit report at https://bugs.php.net/bug.php?id=72173&edit=1
ID: 72173
Comment by: cf0hay at gmail dot com
Reported by: cf0hay at gmail dot com
Summary: very strange reference behavior (bug?) in PHP 5.6,
7.0
Status: Open
Type: Bug
Package: Arrays related
Operating System: Linux 64bit
PHP Version: 7.0.6
Block user comment: N
Private report: N
New Comment:
I consider this a bug, because with integer references this doesn't happen:
<?php
$a = 5;
$ref =& $a; //$ref points to the same value as $a
$ref += 100; //$ref and $a are both 105 because of this
$b = $a; //this copies the value 105 to a new place
$ref += 100; //$ref and $a are 205, but $b remains 105 correctly
var_dump($b);
Previous Comments:
------------------------------------------------------------------------
[2016-05-07 14:16:52] cf0hay at gmail dot com
Description:
------------
Affects both PHP 5.6.21 and PHP 7.0.6 .
- Create an array with some elements
- Iterate over this array by reference
- assign (copy) this array by value to a different variable
- Iterate over the previous array by reference again using the same variable
- the copied array changes at the value which was the last of the original one
Test script:
---------------
<?php
$x = [1,2,3];
foreach($x as &$ref){
$ref += 100;
}
/* $x === [101, 102, 103]
at this point, $ref is bound to the last element of $x, that's OK */
$b = $x;
/* this should logically copy $x to $b *by value* (COW happens) */
$b[0] = 0; /* this should force an array copy in memory */
/* here, $ref should be rebound to the elements of $x by reference */
foreach($x as &$ref){
$ref += 100;
}
/* at this point, $x === [201, 202, 203] which is correct, $ref refers
to the last element of $x again, which is OK,
BUT! As we copied $b by value before, is should stay as is, but the last
element of $b changes to 203! */
var_dump($b);
Expected result:
----------------
array(3) {
[0]=>
int(0)
[1]=>
int(102)
[2]=>
int(103)
}
Actual result:
--------------
array(3) {
[0]=>
int(0)
[1]=>
int(102)
[2]=>
&int(203)
}
------------------------------------------------------------------------
--
Edit this bug report at https://bugs.php.net/bug.php?id=72173&edit=1