我构建了一个具有以下结构的ListNode:
class MyNode {
private $weight;
private $children;
private $t1;
private $t2;
private $t3;
***
more variables
***
function __constructr($weight, $t1, $t2, $t3, $children = array()) {
$this->weight = $weight;
$this->children = $children;
$this->t1 = $t1;
$this->t2 = $t2;
$this->t3 = $t3;
}
现在我创建5个具有相同数据但权重不同的节点。
$n1 = new MyNode(25, 't_1', 't_2', 't_3');
$n2 = new MyNode(30, 't_1', 't_2', 't_3');
$n3 = new MyNode(49, 't_1', 't_2', 't_3');
$n4 = new MyNode(16, 't_1', 't_2', 't_3');
$n5 = new MyNode(62, 't_1', 't_2', 't_3');
请注意,t1,t2和t3可以不同,但对于这5个节点,它们是相同的。而不是在上面做,我想使用某种克隆功能
来做以下事情 $n1 = new MyNode(25, 't_1', 't_2', 't_3');
$n2 = $n1->clone(array('weight' => 30));
$n3 = $n2->clone(array('weight' => 49));
$n4 = $n4->clone(array('weight' => 16));
$n5 = $n5->clone(array('weight' => 62));
clone函数接受一组键,它们是MyNode中我想要更改的变量名及其值。所以数组('weight'=> 30)应该更改 $ this-> weight = 30; 我卡住从数组访问变量。它应该创建一个新节点,其中所有值与其当前节点相同,但仅修改数组中的值。
function clone($changeVariables) {
-----
}
答案 0 :(得分:1)
试试这个:
$obj = clone $this;
foreach ($changeVariables as $field => $val) {
$obj->{$field} = $val;
}
return $obj;
答案 1 :(得分:1)
观察
clone
的保留字__constructr
错误,无法在php construct
以下是您的需求:
class MyNode {
private $weight;
private $children;
private $t1;
private $t2;
private $t3;
function __construct($weight, $t1, $t2, $t3, $children = array()) {
$this->weight = $weight;
$this->children = $children;
$this->t1 = $t1;
$this->t2 = $t2;
$this->t3 = $t3;
}
public function getClone(array $arg) {
$t = clone $this;
foreach ( $arg as $k => $v ) {
$t->{$k} = $v;
}
return $t;
}
}
$n1 = new MyNode(25, 't_1', 't_2', 't_3');
$n2 = $n1->getClone(array(
'weight' => 30
));
print_r($n1);
print_r($n2);
输出
MyNode Object
(
[weight:MyNode:private] => 25
[children:MyNode:private] => Array
(
)
[t1:MyNode:private] => t_1
[t2:MyNode:private] => t_2
[t3:MyNode:private] => t_3
)
MyNode Object
(
[weight:MyNode:private] => 30
[children:MyNode:private] => Array
(
)
[t1:MyNode:private] => t_1
[t2:MyNode:private] => t_2
[t3:MyNode:private] => t_3
)
答案 2 :(得分:0)
Variable variables是一个解决方案:
foreach ($changeVariables as $key => $value) {
$this->{$key} = $value;
}
您可以通过在允许设置之前检查$this->{$key}
是否存在来增强它。
http://php.net/manual/en/language.oop5.cloning.php
总体结果如下:
function clone($changeVariables) {
$newObj = clone $this;
foreach ($changeVariables as $key => $value) {
$newObj->{$key} = $value;
}
return $newObj;
}