Home > Backend Development > PHP Tutorial > Introduction to the implementation method of php cloning (code example)

Introduction to the implementation method of php cloning (code example)

不言
Release: 2023-04-05 10:46:02
forward
2409 people have browsed it

This article brings you an introduction to the implementation method of PHP cloning (code examples). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Some time ago, I looked at object cloning in Java. I felt that I was not very clear about object cloning in PHP, so I did a small test. The code is as follows

<?php

class A{
    public $value = 1;
}

class B{
    public $value = 1;
    public $a = null;

    public function __Construct(){
        $this->a = new A();
    }
}

$b = new B();
$d = 1;
$e = $d;
$e++;
echo "写时复制\n";
echo $d."\n";
echo $e."\n";

echo "------------------------------------\n";

$c = $b;
$c->a->value++;
$c->value++;

echo "对象中的对象变量\n";
echo $b->a->value."\n";
echo $c->a->value."\n";

echo "对象变量中的值变量\n";
echo $b->value."\n";
echo $c->value."\n";

echo "--------------------------------------\n";
$f = clone $b;
$f->value++;
$f->a->value++;

echo "对象变量中的值变量\n";
echo $b->value."\n";
echo $f->value."\n";

echo "对象中的对象变量\n";
echo $b->a->value."\n";
echo $f->a->value."\n";


?>
Copy after login

The running result is as shown

Introduction to the implementation method of php cloning (code example)

is still consistent with Java. The conclusion is as follows

**For the value For variables, simple assignment is copying.
For object variables, simple assignment is a reference.
For object variables, use clone for assignment. The value variable in the object variable is a copy, and the object variable in the object variable is still a reference. **

The above is the detailed content of Introduction to the implementation method of php cloning (code example). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
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