php中对象的引用、浅复制、深复制

概念

引用: 对象之间的等号赋值是引用赋值,两者是同一个资源
浅复制: 值赋值。所有的引用属性(如对象属性)仍然是一个指向原来变量的引用
深复制: 所有引用属性指向复制过来的新对象

测试

引用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class A{
public $obj;
public $name='A';
public function __construct(){
$this->obj = new B();
}
}
class B{
public $name='B';
}
$a = new A();
$b = $a;
var_dump($a,$b); //引用 两者完全相同
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
//结果
class A#1 (2) {
public $obj =>
class B#2 (1) {
public $name =>
string(1) "B"
}
public $name =>
string(1) "A"
}
class A#1 (2) {
public $obj =>
class B#2 (1) {
public $name =>
string(1) "B"
}
public $name =>
string(1) "A"
}

浅复制

1
2
$b = clone $a;
var_dump($a,$b); //浅复制 $b中的obj依旧指向$a中的obj
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
//结果
class A#1 (2) {
public $obj =>
class B#2 (1) {
public $name =>
string(1) "B"
}
public $name =>
string(1) "A"
}
class A#3 (2) {
public $obj =>
class B#2 (1) {
public $name =>
string(1) "B"
}
public $name =>
string(1) "A"
}

深复制

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class A{
public $obj;
public $name='A';
public function __construct(){
$this->obj = new B();
}
public function __clone(){
$this->obj = new B();
}
}
class B{
public $name='B';
}
$a = new A();
$b = clone $a;
var_dump($a,$b); //深复制 $b中的obj依旧指向$a中的obj
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
//结果
class A#1 (2) {
public $obj =>
class B#2 (1) {
public $name =>
string(1) "B"
}
public $name =>
string(1) "A"
}
class A#3 (2) {
public $obj =>
class B#4 (1) {
public $name =>
string(1) "B"
}
public $name =>
string(1) "A"
}