php 深复制

WBOY
Release: 2016-06-06 20:30:22
Original
1140 people have browsed it

<code>php</code><code>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的深复制,浅复制,对吗?
</code>
Copy after login
Copy after login

回复内容:

<code>php</code><code>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的深复制,浅复制,对吗?
</code>
Copy after login
Copy after login

<code>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";
</code>
Copy after login

参考 PHP: 对象复制

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

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

Related labels:
php
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template