PHP object cloning clone usage example

高洛峰
Release: 2023-03-03 20:02:01
Original
1174 people have browsed it

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);
Copy after login

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
Copy after login

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);
Copy after login

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
Copy after login

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!


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