<?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();
?>