如果想在克隆后改变原对象的内容,需要在类中添加一个特殊的 __clone() 方法来重写原本的属性和方法。__clone() 方法只会在对象被克隆的时候自动调用。
例子如下,一看即明:
<?php
class Person {
private $name;
private $age;
public function __construct($name, $age) {
$this->name = $name;
$this->age = $age;
}
public function say() {
echo "my name is " . $this->name . ',';
echo "my age is " . $this->age;
}
public function __clone() {
$this->name = '假' . $this->name;
$this->age = 30;
}
}
$p1 = new Person('张三', 20);
$p1->say(); // 输出结果 my name is 张三,my age is 20
echo '<br />';
$p2 = clone $p1; // 此时触发了__clone 函数,类的属性发生改变,只是改变只是针对克隆之后的类,克隆前的类不发生任何改变
$p2->say(); // 输出结果 my name is 假张三,my age is 30
echo '<br />';
$p1->say(); // 输出结果 my name is 张三,my age is 20