欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

深拷贝和浅拷贝

程序员文章站 2022-07-10 23:33:15
obj = new Test(); } } $test = new TestOne(); /** * 浅拷贝 */ $test_shallow = clone $test; $test_shallow->b = 3; //改变拷贝出来的对象中的$b的值 被拷贝对象的$b的值不变 echo $test... ......
<?php
/**
*深拷贝、浅拷贝
    深拷贝:将被拷贝对象中引用的类一起拷贝
    浅拷贝:拷贝对象时,不能够将对象中引用的其他对象进行拷贝
*
*/

class test{
    public $a = 1;
}

class testone{
    public $b = 2;
    public $obj;
    public function __construct(){
        $this->obj = new test();
    }
}

$test = new testone();

/**
* 浅拷贝
*/

$test_shallow = clone $test;
$test_shallow->b = 3; //改变拷贝出来的对象中的$b的值 被拷贝对象的$b的值不变
echo $test->b."\n"; //输出 2

$test_shallow->obj->a = 5; //改变拷贝出来的对象中引用的obj的$a的值,被拷贝对象中相应的值也会改变,说明两个对象中的obj指向了同一个对象
echo $test->obj->a; //输出5



/**
*深拷贝  无论如何改变$test_deep的值都和$test对象无关
*/
$test_deep = serialize($test);
$test_deep = unserialize($test_shen);
$test_deep->obj->a = 6;
echo $test->obj->a;