- 普通对象的拷贝
普通对象间的拷贝为深拷贝,对拷贝的对象进行修改,不会影响原对象。
<?php
$m = 2;
$n = $m;
$n = 3;
echo $m . PHP_EOL; // 输出2
echo $n . PHP_EOL; // 输出3
- 对象间的拷贝
php中,对象间的拷贝属于浅拷贝,也就是做了一个原对象的引用。
先定义一个类,用于测试
<?php
class Thing {
private $_arr = array();
private $_id = 0;
public function __construct() {
$this->_id = rand(1000, 9999);
}
public function getValue() {
return $this->_arr;
}
public function setValue($value) {
$this->_arr[] = $value;
}
public function modifyValue($index, $value) {
$this->_arr[$index] = $value;
}
public function copy() {
return clone $this;
}
public function getId() {
return $this->_id;
}
public function __clone() {
$this->_id = rand(1000, 9999);
}
}
实例化对象,设置参数,并进行拷贝
<?php
$thing = new Thing();
$thing->setValue(1);
echo str_repeat('-', 5) . 'before copy' . str_repeat('-', 5) . PHP_EOL;
var_dump($thing->getValue());
$copything = $thing;
$copything->setValue(2);
echo str_repeat('-', 5) . 'after copy' . str_repeat('-', 5) . PHP_EOL;
var_dump($thing->getValue());
var_dump($copything->getValue());
上面这段输出的结果是:
-----before copy-----
array(1) {
[0]=>
int(1)
}
-----after copy-----
array(2) {
[0]=>
int(1)
[1]=>
int(2)
}
array(2) {
[0]=>
int(1)
[1]=>
int(2)
}
从结果看,我们对拷贝的对象进行赋值操作,同样影响到了原对象。这种对象间的复制,属于浅拷贝。
要想实现深拷贝,需要使用php的clone函数,我们调用一下类中的copy函数,并对拷贝的对象的参数进行一次修改。
<?php
$thing = new Thing();
$thing->setValue(1);
echo str_repeat('-', 5) . 'before copy' . str_repeat('-', 5) . PHP_EOL;
var_dump($thing->getValue());
$copything = $thing->copy();
$copything->setValue(2);
echo str_repeat('-', 5) . 'after copy' . str_repeat('-', 5) . PHP_EOL;
var_dump($thing->getValue());
var_dump($copything->getValue());
$copything->modifyValue(0, 3);
echo str_repeat('-', 5) . 'modify value' . str_repeat('-', 5) . PHP_EOL;
var_dump($thing->getValue());
var_dump($copything->getValue());
输出结果:
-----before copy-----
array(1) {
[0]=>
int(1)
}
-----after copy-----
array(1) {
[0]=>
int(1)
}
array(2) {
[0]=>
int(1)
[1]=>
int(2)
}
-----modify value-----
array(1) {
[0]=>
int(1)
}
array(2) {
[0]=>
int(3)
[1]=>
int(2)
}
可以看到,这样就实现了深拷贝,拷贝的对象进行赋值操作并修改参数,没有影响到原对象的值。
使用clone函数时,会调用__clone()魔术方法,可以在该方法中对拷贝的对象进行属性的修改。
<?php
$thing = new Thing();
echo str_repeat('-', 5) . 'before copy' . str_repeat('-', 5) . PHP_EOL;
echo $thing->getId() . PHP_EOL;
$thing2 = $thing->copy();
echo str_repeat('-', 5) . 'after copy' . str_repeat('-', 5) . PHP_EOL;
echo 'source id : ' . $thing->getId() . PHP_EOL;
echo 'copy id : ' . $thing2->getId() . PHP_EOL;
输出结果:
-----before copy-----
6974
-----after copy-----
source id : 6974
copy id : 8721
总结:
1. 在对象间进行复制操作的时候,需要注意这种深浅拷贝的问题,否则会对程序运行结果造成非常大的影响。
2. 使用clone函数,进行复制,除了可以完成对象间的深拷贝,还可以在__clone()方法中对拷贝参数的成员变量进行特殊化处理或其他操作。