php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #71009 A reference references multiple variables after clone.
Submitted: 2015-12-01 14:24 UTC Modified: 2015-12-01 15:57 UTC
From: remyfox at hotmail dot com Assigned:
Status: Not a bug Package: Class/Object related
PHP Version: 5.6.16 OS: Windows
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:
37 - 5 = ?
Subscribe to this entry?

 
 [2015-12-01 14:24 UTC] remyfox at hotmail dot com
Description:
------------
The values that are printed are both 11 and 12. I doubt this is correct behaviour.

Test script:
---------------
class A {
    public $z = 10;
}

$a1 = new A();

$z = &$a1->z;

$a2 = clone $a1;

$a1->z = 11;

var_dump($z);

$a2->z = 12;

var_dump($z);


Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2015-12-01 15:57 UTC] leigh@php.net
-Status: Open +Status: Not a bug
 [2015-12-01 15:57 UTC] leigh@php.net
Hi,

This is intentional behaviour and is documented in the manual.

http://php.net/manual/en/language.oop5.cloning.php

"When an object is cloned, PHP 5 will perform a shallow copy of all of the object's properties. Any properties that are references to other variables will remain references."

`$z = &$a1->z;` makes both sides of the assignment references to the same value, and since $a1->z is now a reference it is cloned as a reference.
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Thu Apr 25 23:01:29 2024 UTC