Home > Article > Backend Development > Introduction to the implementation method of php cloning (code example)
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"; ?>
The running result is as shown
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!