Bug #74549 [Nab]: PHP references cause unexpected results
Edit report at https://bugs.php.net/bug.php?id=74549&edit=1
ID: 74549
User updated by: winbill at hotmail dot com
Reported by: winbill at hotmail dot com
Summary: PHP references cause unexpected results
Status: Not a bug
Type: Bug
Package: Scripting Engine problem
Operating System: centos
PHP Version: 7.0Git-2017-05-06 (snap)
Block user comment: N
Private report: N
New Comment:
so how can I "backup" $a after turns $a['foo'] into a reference, and not
affected by the reference ?
the only way is just like $c1 ?
Previous Comments:
------------------------------------------------------------------------
[2017-05-06 10:35:19] requinix@php.net
Thank you for taking the time to write to us, but this is not
a bug. Please double-check the documentation available at
http://www.php.net/manual/ and the instructions on how to
report
a bug at http://bugs.php.net/how-to-report.php
$b = &$a['foo']
turns $a['foo'] into a reference and $b gets a copy of the reference. When you
$c2 = $a
you get a copy of $a, including the reference in [foo] (making three total). $a[foo], $b, and
$c2[foo] will thus all be references to the same value.
------------------------------------------------------------------------
[2017-05-06 10:30:09] winbill at hotmail dot com
Description:
------------
PHP references cause unexpected results
I tested the following script under php 5.3 & 5.6 & 7.0.17
All of them, c2 output {"foo":2}, not {"foo":1}
$a = array('foo' => 1);
$c1 = $a;
$b = &$a['foo'];
$c2 = $a;
$b = 2;
printf("c1:%s\n", json_encode($c1));
printf("c2:%s\n", json_encode($c2)); // output c2:{"foo":2} !
Test script:
---------------
$a = array('foo' => 1);
$c1 = $a;
$b = &$a['foo'];
$c2 = $a;
$b = 2;
printf("c1:%s\n", json_encode($c1));
printf("c2:%s\n", json_encode($c2)); // output c2:{"foo":2} !
Expected result:
----------------
c1:{"foo":1}
c2:{"foo":1}
Actual result:
--------------
c1:{"foo":1}
c2:{"foo":2}
------------------------------------------------------------------------
--
Edit this bug report at https://bugs.php.net/bug.php?id=74549&edit=1
Thread (4 messages)