1
下面的代碼解釋了我遇到的問題,我試圖通過值將$this
賦值給變量,但它通常是通過引用最終分配的,爲什麼?我該怎麼做?
以下腳本是一組兩個類別Test
和TestQuery
。 Test
假設值爲$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;
?>
對於解釋:一個對象是PHP總是被引用。在Java中也是如此,PHP只是複製了行爲。 您必須複製對象的唯一方法的確是使用克隆。 – Matthieu