当前位置:Gxlcms > PHP教程 > php深复制

php深复制

时间:2021-07-01 10:21:17 帮助过:21人阅读

phpclass 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的深复制,浅复制,对吗?

回复内容:

phpclass 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: 对象复制

题主的代码中包含了两个概念对象拷贝和引用。请参考 对象和引用 。

对于深复制和浅复制,不好描述,楼上的代码也体现出来了差别,在献上两张比较直观的图,这样好理解一点吧。
浅复制

深复制

人气教程排行