php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #75692 Changing properties of cloned object can alter the original
Submitted: 2017-12-15 15:38 UTC Modified: -
From: sdaicz at dc dot uba dot ar Assigned:
Status: Open Package: Scripting Engine problem
PHP Version: 7.0.26 OS: All
Private report: No CVE-ID: None
Have you experienced this issue?
Rate the importance of this bug to you:

 [2017-12-15 15:38 UTC] sdaicz at dc dot uba dot ar
Description:
------------
- Clone an object
- Iterate by reference through the attribute values of either the original or the clone
- Change attribute values inside the loop
- Both objects get their attribute values changed instead of only the one intended

Tested on Windows and Linux.
This seems to happen only in php 7.0.
php 7.1 and 5.6 both work as expected.



Test script:
---------------
$a = new \stdClass();
$a->b = 1;
$a->c = 2;
$d = clone $a;
foreach ($d as $key=>&$value) {
	$value += 10;
}
unset($value);
var_dump($a);
var_dump($d);


Expected result:
----------------
Object $a should keep its original values ("b"=>1, "c"=>2). This is what happens in 7.1 and 5.6:

class stdClass#1 (2) {
  public $b =>
  int(1)
  public $c =>
  int(2)
}
class stdClass#2 (2) {
  public $b =>
  int(11)
  public $c =>
  int(12)
}

Actual result:
--------------
Object $a is altered by the loop, resulting in the same values as $d

object(stdClass)#1 (2) {
  ["b"]=>
  int(11)
  ["c"]=>
  int(12)
}
object(stdClass)#2 (2) {
  ["b"]=>
  int(11)
  ["c"]=>
  int(12)
}

Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2017-12-15 15:44 UTC] danack@php.net
> This seems to happen only in php 7.0.
> php 7.1 and 5.6 both work as expected.

The behaviour appears right not only in 7.1 but in 7.2.

PHP 7.0 had "Active Support Until 12 days ago" - also that behaviour is unlikely to be fixed in point version.
 
PHP Copyright © 2001-2019 The PHP Group
All rights reserved.
Last updated: Wed Jun 19 00:01:28 2019 UTC