clone关键字用于复制对象,复制完的对象和源对象保持独立,修改它的属性,不会对源对象造成影响。但是直接赋值引用则不同,它会导致所做的修改也影响到源对象,举例:
<?php
class NbaPlayer{
public $name = '';
}
$james = new NbaPlayer();
$james->name = 'james';
echo 'james`s name is '.$james->name.'<br>';
$james2 = clone $james;//克隆
$james2->name = 'james2';
echo 'after assign :<br>';
echo 'james`s name is '.$james->name.'<br>';
echo 'james2`s name is '.$james2->name.'<br>';
$james3 = $james; //赋值
$james3->name = 'james3';
echo 'after assign:<br>';
echo 'james`s name is '.$james->name.'<br>';
echo 'james2`s name is '.$james3->name.'<br>';
运行后结果:
james`s name is james
after clone :
james`s name is james
james2`s name is james2
after assign:
james`s name is james3
james2`s name is james3