Examples of shallow copying and deep copying in PHP

Source: Internet
Author: User
Tags datetime shallow copy


Weekend free to see the prototype model, which talked about shallow copy and deep copy, think of PHP in the corresponding assignment, cloning and cloning is a shallow copy or deep replication.

Let's take a look at the assignment, such as a resume class, with two attributes of height and weight:

Class Resume

{public

$height;

public $weight;

Public

$workExperience;

}

$ResumeA = new Resume ();

$ResumeB = $ResumeA;

An resume class is instantiated and assigned to the $RESUMEA variable, and the $RESUMEA variable is assigned to $RESUMEB. The PHP manual says:

Since PHP5, the new operator automatically returns a reference, and an object variable no longer holds the value of the entire object. Just save an identifier to access the real object content. When an object is passed as a parameter, returned as a result, or assigned to another variable, another variable is not the same as the original reference, except that they all hold a copy of the same identifier that points to the true content of the same object.

Therefore, if the Height property is modified by $resumeb, the $resumea will also change accordingly. If you want to replicate an entirely new object, you can do so by using clone, such as:

$ResumeB = Clone $ResumeA;

The $resumea value is then copied to the new variable $resumeb, changing one does not affect the other, modifying the Height property in the $resumeb, $ResumeA does not change.
However, if the class references other objects, all references still point to the original object. Cloning this way is a shallow copy. All the variables of the assigned object also have the same value as the original object, and all references to other objects still point to the original object.

If the above class Workexperience as a reference to the Workexperience class, when cloning, the Workexperience attribute before or after the clone points to the same object content.

In contrast to a shallow copy, a deep copy is a deep copy that refers to a variable that references an object to a new object that has been copied, rather than to the original referenced object.

There are two ways to achieve deep replication in PHP. The first is the __clone Magic method:

Public Function __clone ()

{

$this->workexperience = new Workexperience ();

}

Deep replication involves a deep hierarchy, which requires knowing several layers and then implementing each layer sequentially through the clone Magic method implementation. There is also a way to serialize an object before deserializing it by serializing it, such as:

$ResumeB = Unserialize (serialize ($ResumeA));

Clone is also a common copy method, the purpose of sorting is to record the clone is a shallow copy, you need to pay attention to the reference of the object

Let's take a more practical example to illustrate the consequences of this shallow copy of PHP clone:

Class testclass {   public  $str _data    public  $obj _data} $
Datetimeobj = new datetime ("2014-07-05",  new datetimezone ("UTC"));
$obj 1 = new testclass ();
$obj 1->str_data = "AAA";
$obj 1->obj_data =  $DATETIMEOBJ;
$obj 2 = clone  $obj 1;
Var_dump ($obj 1);     // str_data: "AAA"   obj_data: "2014-07-05 00:00:00" Var_dump ($obj 2);     // str_data: "AAA"   obj_data: "2014-07-05 00:00:00" $
Obj2->str_data = "BBB"; $obj 2->obj_data->add (new dateinterval (' p10d '));       //to $obj2->obj _date  time increased by 10 days Var_dump ($obj 1);      // str_data: "AAA"    obj_
Data: "2014-07-15 00:00:00"   !!!! Var_dump ($obj 2);      // str_data: "BBB"    obj_data: "2014-07-15  00:00:00 "Var_Dump ($DATETIMEOBJ)   // 2014-07-15 00:00:00 " 


Clatter can see the problem more clearly. In general, you use clone to copy objects, hoping to completely separate two objects, do not want to have any association between them, but because of the clone of the shallow copy of the characteristics, sometimes do not expect the results, in the example above,
1) $obj 1->obj_data = $dateTimeObj This sentence is actually an assignment of a reference type. Remember that the direct assignment of objects in PHP mentioned earlier is a reference operation? Unless you use $obj1->obj_dat = Clone $DATATIMEOBJ!

2 $obj 2 = clone $obj 1 This sentence generates a shallow copy object of a Obj1 object and assigns it to OBJ2. Because it is a shallow copy, obj2 in the Obj_data is also a reference to $datetimeobj!

3) $DATETIMEOBJ, $obj 1->obj_data, $obj 2->obj_data is actually a reference to the same memory area object data, so modifying any one of them will affect the other two!

How to solve this problem? Using the __clone method in PHP to convert a shallow copy into a deep copy (this method is somewhat similar to the concept of copy constructor in C + +, but the execution process is not the same)

Class testclass { public  $str _data  public  $obj _data;  public function _ _clone ()  {    $this->obj_data = clone  $this->obj_data;} $dateTimeObj
 = new datetime ("2014-07-05",  new datetimezone ("UTC"));
$obj 1 = new testclass ();
$obj 1->str_data = "AAA";
$obj 1->obj_data =  $DATETIMEOBJ;
$obj 2 = clone  $obj 1; Var_dump ($obj 1);   // str_data: "AAA"   obj_data: "2014-07-05 00:00:00" Var_dump ($ OBJ2)   // str_data: "AAA"   obj_data: "2014-07-05 00:00:00" $obj 2->str_data
 = "BBB";
$obj 2->obj_data->add (new dateinterval (' p10d ')); Var_dump ($obj 1);   // str_data: "AAA"   obj_data: "2014-07-05 00:00:00" Var_dump ($ OBJ2);   // str_data: "AAA"   obj_data: "2014-07-15 00:00:00" Var_dump ($DATETIMEOBJ);   //"2014-07-05 00:00: 00 " 


About __clone (), PHP official documentation: Once The cloing is complete, if a __clone () is defined, then the newly created object ' s __ Clone () method would be called, to allow any necessary properties that need to be changed.

According to this definition, the __clone method can actually do a lot of things, but all I can think of now is the application of the scene of turning a shallow copy into a deep copy, and if there are other uses, you are welcome to propose

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.