php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #38788 cloning and and references inside the objects
Submitted: 2006-09-12 12:18 UTC Modified: 2006-09-12 12:39 UTC
From: j dot henge-ernst at interexa dot de Assigned: dmitry (profile)
Status: Not a bug Package: Scripting Engine problem
PHP Version: 5.1.6 OS: linux
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: j dot henge-ernst at interexa dot de
New email:
PHP Version: OS:

 

 [2006-09-12 12:18 UTC] j dot henge-ernst at interexa dot de
Description:
------------
I encountered a problem similar to the bug #27268
http://bugs.php.net/bug.php?id=27268

The attribut b of the cloned object is still pointing to the attribut of its original object. So changing the attribut in the cloned object also changes the attribute in the original object.

Reproduce code:
---------------
<?php

class a {
    protected $a = array();
    protected $b = '';
    public function __construct($b) { $this->b = $b; $this->a['f'] = &$this->b; }
    public function setB($b) { $this->b = $b; }
    public function printB() { echo __CLASS__ . $this->b . '/' . $this->a['f'] ."\n"; }
    public function __clone() { unset($this->a['f']); $this->a['f'] = &$this->b; }
}

$x1 = new a(5);
$x2 = clone $x1;
$x2->setB(7);
$x1->printB();
$x2->printB();



Expected result:
----------------
a5/5
a7/7

Actual result:
--------------
a7/7
a7/7

Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2006-09-12 12:39 UTC] dmitry@php.net
This is not a BUG, but expected behavior.
look into your __clone() method. $this->a['f'] and $this->b are references to the same variable (to $x1->b). You destroy $this->a['f'], but not $this->b that still point ot $x1->b, and makes $this->a['f'] reference to the same var again.

You would probably like change your code to:

public function __clone() { unset($this->b); $this->a['f'] =
&$this->b; }

Now it works as you expected.

 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Sat May 18 10:01:32 2024 UTC