克隆不为我工作吗? [英] Clone is not working for me?
问题描述
我有一个类ClassDummy
的对象$objDummy
,另一个是
I have an object $objDummy
of some class ClassDummy
and another is as
$objClone = clone $objDummy;
然后我在$objClone
中进行任何更改,$objDummy
也进行了更改.
我不想那样做.
我怎样才能使它正常工作?
Then I make any change in $objClone
, $objDummy
is also changed.
I do not want to do that.
How can I get this to work?
作为对克里斯的回应. 这是一个例子
In response to Chris. Here is an example
<?php
class myAnotherObject{
public $myAnotherVar =10;
}
class myObject {
public $myVar = false;
function __construct() {
$this->myVar = new myAnotherObject();
}
}
$nl = "\n";
//*
$nl = '<br />';
//*/
$obj1 = new myObject();
echo 'obj1->myVar->myAnotherVar: '.$obj1->myVar->myAnotherVar;
$obj2 = clone $obj1;
echo $nl.'obj1->myVar->myAnotherVar: '.$obj1->myVar->myAnotherVar.', obj2->myVar->myAnotherVar: '.$obj2->myVar->myAnotherVar;
$obj2->myVar->myAnotherVar = 20;
echo $nl.'obj1->myVar->myAnotherVar: '.$obj1->myVar->myAnotherVar.', obj2->myVar->myAnotherVar: '.$obj2->myVar->myAnotherVar;
输出为
obj1->myVar->myAnotherVar: 10
obj1->myVar->myAnotherVar: 10, obj2->myVar->myAnotherVar: 10
obj1->myVar->myAnotherVar: 20, obj2->myVar->myAnotherVar: 20
推荐答案
您是否正在实现__clone()
方法? 有关克隆的PHP文档中的示例将比我可能更好地解释这一点.能够.特别是您对这部分感兴趣,
Are you implementing the __clone()
method? The examples in the PHP documentation on cloning will explain this better than I possibly can. Specifically you're interested in this part,
克隆对象后,PHP 5将 对所有 对象的属性.任何属性 指其他 变量,将保留引用.
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.
克隆完成后,如果 定义__clone()方法,然后定义新创建的对象的__clone() 方法将被调用,以允许任何 需要的必要属性 改变了.
Once the cloning is complete, if a __clone() method is defined, then the newly created object's __clone() method will be called, to allow any necessary properties that need to be changed.
更新
根据对问题的更新,您确实缺少__clone()
的实现.由于myObject
的$myVar
成员本身就是一个对象,因此您也需要对其进行克隆.这是您的myObject
类的外观,
UPDATE
Based on your update to the question, you're indeed missing the implementation of __clone()
. Since the $myVar
member of myObject
is itself an object, you need to clone that as well. Here's what your myObject
class should look like,
class myObject {
public $myVar = false;
function __construct() {
$this->myVar = new myAnotherObject();
}
function __clone() {
$this->myVar = clone $this->myVar;
}
}
输出将变为以下内容,
obj1->myVar->myAnotherVar: 10
obj1->myVar->myAnotherVar: 10, obj2->myVar->myAnotherVar: 10
obj1->myVar->myAnotherVar: 10, obj2->myVar->myAnotherVar: 20
这篇关于克隆不为我工作吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!