PHP clone 关键字
实例
创建对象的副本:
<?php
class MyClass {
public $color;
public $amount;
}
$obj = new MyClass();
$obj->color = "red";
$obj->amount = 5;
$copy = clone $obj;
print_r($copy);
?>
亲自试一试 »
class MyClass {
public $color;
public $amount;
}
$obj = new MyClass();
$obj->color = "red";
$obj->amount = 5;
$copy = clone $obj;
print_r($copy);
?>
定义和用法
clone
关键字用于创建对象的副本。
如果任何属性是对另一个变量或对象的引用,则仅复制该引用。 对象总是通过引用传递,因此如果原始对象的属性中有另一个对象,则副本将指向同一个对象。 可以通过在类中创建 __clone()
方法来更改此行为。
相关页面
在我们的 PHP 类和对象教程中了解更多关于类的信息。
更多实例
实例
创建具有引用的对象的副本:
<?php
class MyClass {
public $amount;
}
// Create an object with a reference
$value = 5;
$obj = new MyClass();
$obj->amount = &$value;
// Clone the object
$copy = clone $obj;
// Change the value in the original object
$obj->amount = 6;
// The copy is changed
print_r($copy);
?>
亲自试一试 »
class MyClass {
public $amount;
}
// Create an object with a reference
$value = 5;
$obj = new MyClass();
$obj->amount = &$value;
// Clone the object
$copy = clone $obj;
// Change the value in the original object
$obj->amount = 6;
// The copy is changed
print_r($copy);
?>
实例
使用 __clone()
方法来中断复制对象中的引用:
<?php
class MyClass {
public $amount;
public function __clone() {
$value = $this->amount;
unset($this->amount); // Unset breaks references
$this->amount = $value;
}
}
// Create an object with a reference
$value = 5;
$obj = new MyClass();
$obj->amount = &$value;
// Clone the object
$copy = clone $obj;
// Change the value in the original object
$obj->amount = 6;
// The copy is not changed
print_r($copy);
?>
亲自试一试 »
class MyClass {
public $amount;
public function __clone() {
$value = $this->amount;
unset($this->amount); // Unset breaks references
$this->amount = $value;
}
}
// Create an object with a reference
$value = 5;
$obj = new MyClass();
$obj->amount = &$value;
// Clone the object
$copy = clone $obj;
// Change the value in the original object
$obj->amount = 6;
// The copy is not changed
print_r($copy);
?>