2013-03-21 90 views
1

我建立了一個ListNode具有以下結構:數組內的變量名稱。改變它們的值PHP

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; Im卡住訪問數組中的變量。它應該創建一個新的節點,其所有值與其當前節點相同,但只修改數組中的值。

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

回答

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; 
} 
+0

改變了cu的值rrent節點,但我想創建一個與當前節點具有完全相同數據的當前節點的克隆,但只有不同之處在於數組中的任何節點。 – GGio 2013-03-21 14:19:41

+0

感謝這就是我一直在尋找的。 – GGio 2013-03-21 14:22:52

1

試試這個:

$obj = clone $this; 

foreach ($changeVariables as $field => $val) { 
    $obj->{$field} = $val; 
} 
return $obj; 
1

觀察

  • 無法實現方法或函數調用clone其保留字
  • 這不是如何克隆對象在PHP
  • __constructr是錯誤的,並設置construct在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 
)