Bug #74549 [Nab]: PHP references cause unexpected results

From: Date: Mon, 08 May 2017 03:50:38 +0000
Subject: Bug #74549 [Nab]: PHP references cause unexpected results
References: 1  Groups: php.bugs 
Request: Send a blank email to php-bugs+get-208991@lists.php.net to get a copy of this message
Edit report at https://bugs.php.net/bug.php?id=74549&edit=1 ID: 74549 Updated by: requinix@php.net 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: Most of the time the answer is to not use references. Otherwise it depends on the code. Try an online forum or mailing list for a better answer. Previous Comments: ------------------------------------------------------------------------ [2017-05-08 02:11:34] winbill at hotmail dot com 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 ? ------------------------------------------------------------------------ [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

« previous php.bugs (#208991) next »