php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #74549 PHP references cause unexpected results
Submitted: 2017-05-06 10:30 UTC Modified: 2017-05-08 03:50 UTC
From: winbill at hotmail dot com Assigned:
Status: Not a bug Package: Scripting Engine problem
PHP Version: 7.0Git-2017-05-06 (snap) OS: centos
Private report: No CVE-ID: None
View Add Comment Developer Edit
Welcome! If you don't have a Git account, you can't do anything here.
You can add a comment by following this link or if you reported this bug, you can edit this bug over here.
(description)
Block user comment
Status: Assign to:
Package:
Bug Type:
Summary:
From: winbill at hotmail dot com
New email:
PHP Version: OS:

 

 [2017-05-06 10:30 UTC] 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}

Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2017-05-06 10:35 UTC] requinix@php.net
-Status: Open +Status: Not a bug
 [2017-05-06 10:35 UTC] 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-08 02:11 UTC] 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-08 03:50 UTC] requinix@php.net
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.
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Thu Apr 25 23:01:29 2024 UTC