<?php
class Person
{
var $name;
function __construct() {
$this->name = "小aa明" . '<br />';
}
function say() {
echo $this->name . "在說話";
}
}
$new = new Person();
$new->say();
$clone = $new;
$clone->say();
$new->name = "校長";
$new->say();
$clone->say();
因為$new和$clone都是指向同一個記憶體區的引用,所以修改任何一個物件都會同時修改另外一個物件。
<?php
class Person
{
var $name;
function __construct() {
$this->name = "小aa明" . '<br />';
}
function say() {
echo $this->name . "在說話";
}
}
$new = new Person();
$new->say();
$clone = clone $new;
$clone->say();
$new->name = "校長";
$new->say();
$clone->say();
因為clone的方式實際上是對整個物件的記憶體區域進行了一次複製並用新的物件變數指向新的記憶體, 因此賦值後的物件和源物件相互之間是基本來說獨立的。
可以在物件類中定義一個__clone()方法來調整物件的克隆行為。此方法的程式碼將在克隆操作期間執行。除了將所有現有物件成員複製到目標物件之外,還會執行__clone()方法指定的操作
<?php
class Fruit
{
private $name = "水果";
private $color = "顏色";
public function setName($name) {
$this->name = $name;
}
public function setColor($color) {
$this->color = $color;
}
function showColor() {
return $this->color . '的' . $this->name . "<br/>";
}
function __destruct() {
echo "被吃掉了(物件被回收) <br/>";
}
function __clone() {
$this->name = "克隆水果";
}
}
$apple = new Fruit();
$apple->setName("大蘋果");
$apple->setColor("紅色");
echo $apple->showColor();
$clone_apple = clone $apple;
$clone_apple->setColor("青色");
echo $clone_apple->showColor();
?>