1

我构建了一个具有以下结构的 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));

克隆函数采用键数组作为 MyNode 中我想要更改的变量名称及其值。所以array('weight' => 30)应该改变$this->weight = 30; 我坚持从数组访问变量。它应该创建一个所有值与其当前节点相同的新节点,但只修改数组中的值。

   function clone($changeVariables) {
      -----
   }
4

3 回答 3

1

试试这个:

$obj = clone $this;

foreach ($changeVariables as $field => $val) {
    $obj->{$field} = $val;
}
return $obj;
于 2013-03-21T14:20:35.570 回答
1

观察

  • 您不能实现称为clone保留字的方法或函数
  • 那不是如何在 php 中克隆对象
  • __constructrconstruct在 php中设置是错误且无效的方法

这是您需要的:

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
)
于 2013-03-21T14:25:27.733 回答
0

可变变量是一种解决方案:

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;
}
于 2013-03-21T14:19:07.450 回答