2016-10-22 34 views
1

下面的代碼解釋了我遇到的問題,我試圖通過值將$this賦值給變量,但它通常是通過引用最終分配的,爲什麼?我該怎麼做?

以下腳本是一組兩個類別TestTestQueryTest假設值爲$num屬性,則腳本調用Test->exist(),該值創建兩個變量:$original「按值」和$obj作爲參考,此時兩者都相同。最後腳本調用TestQuery->doit($obj);暗示TestQuery將修改$obj$code,如果$num的值爲2,但結果無效,因爲exist()方法中的$original$obj的值是新近相同的。

<?php 

class TestQuery{ 
    public function doit(&$obj) 
    { 
     if ($obj->getNum() == 2) 
      $obj->setCode(55); 
    } 
} 

class Test { 
    public $code; 
    public $num; 

    public function setCode($code) { $this->code= $code; } 
    public function getCode($code) { return $this->code; } 

    public function getNum() 
    { 
     return $this->num; 
    } 

    public function exist() 
    { 
     $original = $this; 
     $obj =& $this; 

     // The same objects ...(valid) 
     echo "<xmp>"; 
     print_r($original); 
     echo " VS "; 
     print_r($obj); 
     echo "</xmp>"; 

     $tc = new TestQuery(); 
     $tc->doit($obj); 

     // The same objects newly... (invalid, hoping different) 
     echo "<xmp>"; 
     print_r($original); 
     echo " VS "; 
     print_r($obj); 
     echo "</xmp>"; 
    } 

} 

$t = new Test(); 
$t->num = 2; 
$t->exist(); 

exit; 

?> 

回答

0

我發現的解決方案是使用clone關鍵字。

$original = clone $this; 
+1

對於解釋:一個對象是PHP總是被引用。在Java中也是如此,PHP只是複製了行爲。 您必須複製對象的唯一方法的確是使用克隆。 – Matthieu

相關問題