457   PHP

一,背景

1,有时候我们需要一个新对象,跟原对象的结构相同,我们可以这样实现

$test = new test();
$new_test = $test;

但是,PHP中直接赋值的方式属于浅拷贝,新对象和原对象引用同一内存地址,当修改这个新对象时,将会影响原对象。

2,为了避免这种情况,PHP就有了方法clone,当使用clone复制对象时,将会调用对象中的方法 __clone(),并且会重新生成一个不同引用内存地址的对象,当修改这个新对象的属性时,原对象属性保持不变。

 

二,示例代码

class test{
	//私有属性
	private $name;
	
	//实例化对象时被调用
	public function __construct() {
		echo 'initializing',"\n";
	}

	public function getName(){
		return $this->name;
	}
	
	public function setName($name){
		$this->name = $name;
	}
	
	// 复制对象会被调用,深拷贝之后,修改新的对象不会影响原来的对象
	public function __clone(){
		echo 'clone obj',"\n";
	}
	
}


$test = new test();
echo 'set test name',"\n";
$test->setName('test');
echo 'get test name',"\n";
echo $test->getName(),"\n";


// 直接赋值方式,引用同一内存地址
// 浅拷贝,修改新的对象将会影响原对象
$new_test = $test;
echo "\n";
echo 'set new_test name',"\n";
$new_test->setName('new_test');
echo 'get new_test name',"\n";
echo $new_test->getName(),"\n";

// 原对象的值被修改了
echo "\n";
echo 'get test name',"\n";
echo $test->getName(),"\n";


echo "\n";
echo 'set test name',"\n";
$test->setName('test');


// 采用clone复制对象
// 深拷贝,修改新的对象不会影响原对象
echo "\n";
echo 'clone_test obj',"\n";
$clone_test = clone $test;

echo "\n";
echo 'set clone_test name',"\n";
$clone_test->setName('clone_test');
echo 'get clone_test name',"\n";
echo $clone_test->getName(),"\n";

// 原对象的值还是不变
echo "\n";
echo 'get test name',"\n";
echo $test->getName(),"\n";



三,测试结果

C:\Users\luckybird\Desktop\test>php test.php
initializing
set test name
get test name
test

set new_test name
get new_test name
new_test

get test name
new_test

set test name

clone_test obj
clone obj

set clone_test name
get clone_test name
clone_test

get test name
test




Leave a Reply

Your email address will not be published. Required fields are marked *