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
Welcome back! If you're the original bug submitter, here's where you can edit the bug or add additional notes.
If you forgot your password, you can retrieve your password here.
Password:
Status:
Package:
Bug Type:
Summary:
From: remyfox at hotmail dot com
New email:
PHP Version: OS:

 

 [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

Pull Requests

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: Fri Oct 18 02:01:27 2024 UTC