Home  >  Article  >  Backend Development  >  PHP object cloning clone usage example

PHP object cloning clone usage example

高洛峰
高洛峰Original
2016-12-21 14:04:421169browse

The example in this article describes the usage of PHP object cloning clone. Share it with everyone for your reference, the details are as follows:

Shallow cloning: only clone the non-object non-resource data in the object, that is, the attributes in the object store the object type, then there will be incomplete cloning

<?php
class B{
 public $val = 10;
}
class A{
 public $val = 20;
 public $b;
 public function __construct(){
  $this->b = new B();
 }
}
$obj_a = new A();
$obj_b = clone $obj_a;
$obj_a->val = 30;
$obj_a->b->val = 40;
var_dump($obj_a);
echo &#39;<br>&#39;;
var_dump($obj_b);

Run The results are as follows:

object(A)[1]
 public &#39;val&#39; => int 30
 public &#39;b&#39; =>
 object(B)[2]
  public &#39;val&#39; => int 40
 
object(A)[3]
 public &#39;val&#39; => int 20
 public &#39;b&#39; =>
 object(B)[2]
  public &#39;val&#39; => int 40

Deep cloning: All attribute data of an object are completely copied. You need to use the magic method __clone(), and implement deep cloning in it

<?php
class B{
 public $val = 10;
}
class A{
 public $val = 20;
 public $b;
 public function __construct(){
  $this->b = new B();
 }
 public function __clone(){
  $this->b = clone $this->b;
 }
}
$obj_a = new A();
$obj_b = clone $obj_a;
$obj_a->val = 30;
$obj_a->b->val = 40;
var_dump($obj_a);
echo &#39;<br>&#39;;
var_dump($obj_b);

The running results are as follows:

object(A)[1]
 public &#39;val&#39; => int 30
 public &#39;b&#39; =>
 object(B)[2]
  public &#39;val&#39; => int 40
 
object(A)[3]
 public &#39;val&#39; => int 20
 public &#39;b&#39; =>
 object(B)[4]
  public &#39;val&#39; => int 10

I hope this article will be helpful to everyone in PHP programming.

For more articles related to PHP object cloning clone usage examples, please pay attention to the PHP Chinese website!


Statement:
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