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: 2020-10-29 17:26 UTC
From: sdaicz at dc dot uba dot ar Assigned: cmb (profile)
Status: Closed Package: Scripting Engine problem
PHP Version: 7.0.26 OS: All
Private report: No CVE-ID: None
View Add Comment Developer Edit
Anyone can comment on a bug. Have a simpler test case? Does it work for you on a different platform? Let us know!
Just going to say 'Me too!'? Don't clutter the database with that please !
Your email address:
MUST BE VALID
Solve the problem:
1 + 22 = ?
Subscribe to this entry?

 
 [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.
 [2020-10-29 17:26 UTC] cmb@php.net
-Status: Open +Status: Closed -Assigned To: +Assigned To: cmb
 [2020-10-29 17:26 UTC] cmb@php.net
Indeed, works again as of PHP 7.1.0[1], and PHP 7.0 is EOL.

[1] <https://3v4l.org/5BbnE>
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Thu Apr 25 07:01:31 2024 UTC