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
 [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 11:01:34 2024 UTC