【发布时间】:2014-10-14 18:15:49
【问题描述】:
所以在过去的几天里,我一直在努力让课程正确克隆。问题是克隆不会删除/重做任何传递引用。结果是,主数据对象仍然作为引用传递,从而完全否定了克隆的效果。
这是问题的简化版本:
class my_class {
private $data;
public $var1;
public $var2;
public $var3;
public function __construct() {
$this->data = new stdClass;
$this->data->var1 = 'a';
$this->data->var2 = 'b';
$this->data->var3 = 'c';
$this->var1 = &$this->data->var1;
$this->var2 = &$this->data->var2;
$this->var3 = &$this->data->var3;
}
}
$original = new my_class;
$new = clone $original;
$new->var3 = 'd';
// Output Should Be "c", outputs "d"
echo $original->var3;
在此处查看实际操作:http://3v4l.org/nm6NW
我的问题:如何使用__clone() 将输出从“d”更正为“c”?
请尽你所能提供帮助!?
更新
我最终让__clone() 触发了一个错误并创建了一个名为make_clone() 的函数来标准化克隆。
__clone() 现在看起来像:
public function __clone() {
$trace = debug_backtrace();
$fmt = 'Invalid clone in <b>%4$s</b> on line <b>%5$s</b>. Because of how cloning works, and how references are configured within the class, extensions of %1$s cannot be cloned. Please use <code>make_clone()</code> instead. Error triggered';
trigger_error(sprintf($fmt, $trace[0]['class'], $trace[0]['function'], 'clone', $trace[0]['file'], $trace[0]['line']), E_USER_NOTICE);
}
而make_clone() 看起来像:
public function make_clone() {
// This line recreates the current instance at its' current state.
$clone = new $this(generate::string($this->object));
// In my class $this->input is a type of history state.
// The history of both the original and the clone should match
$clone->input = $this->input;
return $clone;
}
【问题讨论】:
-
标准的
clone方法执行浅拷贝。听起来你需要一个深拷贝,所以你需要你的 clone 方法来克隆$this->object。 -
试过了,还是不行
-
我不确定这与传递引用有什么关系。这仅适用于您调用函数时。
-
你能做一个简化的测试用例,你可以在这里发布。试图从 github 上的数百行代码中弄清楚你在做什么是很困难的。此外,一旦问题得到解决并且您更新了 github,这些链接将失效。
-
@barmar 至于传递引用,
$a = &$b与 `$a = $b' 不同。引用传递不限于函数/方法。
标签: php oop clone pass-by-reference