php4面向對象最大的缺點之一,是將對象視為另一種數據類型,這使得很多常見的OOP方法無法使用,如設計模式。這些OOP方法依賴於將對象作為引用傳遞給其他的類的方法,而不是作為值傳遞。幸好PHP解決了這個問題。現在所有對象在默認情況下都被視為引用。但是因為所有對象對被視為引用而不是值,所以現在復制對象顯得更難了。如果嘗試復制一個對象,這是會指向原對象的地址。為了解決復制問題,PHP提供了一種克隆顯示對象的方法。
實例如下:
首先介紹使用clone關鍵字克隆對象:
name = $na;
}
function getName()
{
return $this->name;
}
function setNum($nu)
{
$this->num = $nu;
}
function getNum()
{
return $this->num;
}
}
$test = new TestClone();
$test->setName("tianxin");
$test->setNum(123456);
echo $test->getName();
echo $test->getNum()."
";
$test2 = clone $test;
$test2->setName("liwei");
echo $test->getName();
echo $test->getNum()."
";
echo $test2->getName();
echo $test2->getNum();
?>
運行結果:
tian123456 tian123456 xia123456
PHP5定義了一個特殊的方法名“__clone()”方法,是在對象克隆時自動調用的方法,用“__clone()”方法將建立一個與原對象擁有相同屬性和方法的對象,如果想在克隆後改變原對象的內容,需要在__clone()中重寫原本的屬性和方法, ”__clone()”方法可以沒有參數,它自動包含$this和$that兩個指針,$this指向復本,而$that指向原本;
name = $na;
}
function getName()
{
return $this->name;
}
function setNum($nu)
{
$this->num = $nu;
}
function getNum()
{
return $this->num;
}
function __clone()
{
$this->name = "huang";
}
}
$test = new TestClone();
$test->setName("tian");
$test->setNum(123456);
echo $test->getName();
echo $test->getNum()."
";
$test2 = clone $test;
// $test2->setName("xia");
echo $test->getName();
echo $test->getNum()."
";
echo $test2->getName();
echo $test2->getNum();
?>
tian123456 tian123456 huang123456
name = $name;
$this->sex = $sex;
$this->age = $age;
}
// 這個人可以說話的方法, 說出自己的屬性
function say() {
echo "我的名字叫:" . $this->name . " 性別:" . $this->sex . " 我的年齡是:" . $this
->age . "
";
}
// 對象克隆時自動調用的方法, 如果想在克隆後改變原對象的內容,需要在__clone()中重寫原來的屬性和方法。
function __clone() {
// $this 指的復本p2, 而$that 是指向原本p1,這樣就在本方法裡,改變了復本的屬性。
$this->name = "我是復制的張三$that->name";
// $this->age = 30;
}
}
$p1 = new Person ( "張三", "男", 20 );
$p2 = clone $p1;
$p1->say ();
$p2->say ();
?>
運行後的結果:
我的名字叫:張三 性別:男 我的年齡是:20 我的名字叫:我是復制的張三 性別:男 我的年齡是:20