php 深复制
程序员文章站
2024-01-24 11:05:10
...
php
class test{ public $num = 100; } $a = new test(); $b = clone $a; $a->num = 200; echo $b->num;//100 class test{ public $num = 100; } $a = new test(); $b = $a; $a->num = 200; echo $b->num;//200 //数组 $a = [1,2,3]; $b = $a; $a[1] = 5; var_dump($b);//[1,2,3] $a = [1,2,3]; $b = &$a; $a[1] = 5; var_dump($b);//[1,5,3] //以上就是php的深复制,浅复制,对吗?
回复内容:
php
class test{ public $num = 100; } $a = new test(); $b = clone $a; $a->num = 200; echo $b->num;//100 class test{ public $num = 100; } $a = new test(); $b = $a; $a->num = 200; echo $b->num;//200 //数组 $a = [1,2,3]; $b = $a; $a[1] = 5; var_dump($b);//[1,2,3] $a = [1,2,3]; $b = &$a; $a[1] = 5; var_dump($b);//[1,5,3] //以上就是php的深复制,浅复制,对吗?
class SubTest {
public $num = 100;
}
class Test {
public $child;
function __construct($child){
$this->child = $child;
}
}
$a = new Test(new SubTest());
// 这里进行浅拷贝
$b = clone $a;
$b->child->num = 200;
// 以下输出均是 200
echo $a->child->num, "\n";
echo $b->child->num, "\n";
class Test2 {
public $child;
function __construct($child){
$this->child = $child;
}
// clone 完成时,此方法会被调用,在此完成深拷贝动作
function __clone() {
$this->child = clone $this->child;
}
}
$a = new Test2(new SubTest());
// 这里进行深拷贝
$b = clone $a;
$b->child->num = 200;
// 以下输出是 100, 200
echo $a->child->num, "\n";
echo $b->child->num, "\n";
参考 PHP: 对象复制
题主的代码中包含了两个概念对象拷贝和引用。请参考 对象和引用 。
对于深复制和浅复制,不好描述,楼上的代码也体现出来了差别,在献上两张比较直观的图,这样好理解一点吧。浅复制
:深复制
:
上一篇: 有关相见恨晚的文章推荐5篇
下一篇: 队列是什么意思?