search
HomeBackend DevelopmentPHP Tutorialphp5 object copy, clone, shallow copy and deep copy

The origin of object copy
Why objects have the concept of "copying"? This is closely related to the way objects are passed by value in PHP5. Let's take a look at the following simple code

php code

* /**
* * TV
**/
* class Television
* {
* /**
* * screen height
**/
* protected
$_screenLength = 300;
*
* /**
* * screen width
**/
* protected
$_screenHight = 200;
*
* /**
* * TV appearance color
**/
* protected
$_color = 'black';
*
* /**
* * Return to TV appearance color
**/
* public
function getColor()
* {
* return
$this->_color;
* }
*
* /**
* * Set TV appearance color
**/
* public
function setColor($color)
* {
* $this->_color = (string)$color;
* return
$this;
* }
* }
*
* $tv1 = new Television();
* $tv2 = $tv1;


This code defines a television class Television, $tv1 is an instance of a television, and then we assign the value of $tv1 to $t2 according to the ordinary variable assignment method. So now we have two TVs $tv1 and $tv2. Is this really the case? Let's test it out.

PHP code

* echo
'color of tv1 is: ' . $tv1->getColor();//The color of tv1 is black
* echo
'
';

* echo
'color of tv2 is: ' . $tv2->getColor();//The color of tv2 is black
* echo
'
';

*
* //Paint tv2 white
* $tv2->setColor('white');
*
* echo
'color of tv2 is: ' . $tv2->getColor();//The color of tv2 is white
* echo
'
';

* echo
'color of tv1 is: ' . $tv1->getColor();//The color of tv1 is white


First we see that the colors of tv1 and tv2 are both black. Now we want tv2 to change its color, so we set its color to white. Let’s look at the color of tv2 again. It has indeed become white, which seems to satisfy our needs. However, it did not go as smoothly as expected. When we looked at the color of tv1, we found that tv1 also changed from black to white. We did not reset the color of tv1. Why did tv1 change black to white? This is because the assignment and value transfer of objects in PHP5 are all done by "reference". PHP5 uses Zend Engine II, and objects are stored in a separate structure Object Store, instead of being stored in Zval like other general variables (in PHP4, objects are stored in Zval like general variables). Only the pointer to the object is stored in Zval rather than the content (value). When we copy an object or pass an object as a parameter to a function, we do not need to copy the data. Just keep the same object pointer and notify the Object Store that this particular object now points to via another zval. Since the object itself is located in the Object Store, any changes we make to it will affect all zval structures holding pointers to the object - manifested in the program as any changes to the target object will affect the source object. .This makes it look like PHP objects are always passed by reference. So the above tv2 and tv1 actually point to the same TV instance, and the operations we do on tv1 or tv2 are actually for this same instance. So our "copy" failed.It seems that direct variable assignment cannot copy objects. For this reason, PHP5 provides an operation specifically for copying objects, which is clone. This is where object copying comes in.


Use clone to copy objects
We now use PHP5’s clone language structure to copy objects, the code is as follows:
[size=+0]PHP code

* [size=+0]$tv1 = new Television();
* $tv2 = clone $tv1;
*

* echo
'color of tv1 is: ' . $tv1->getColor();//The color of tv1 is black
* echo
'
';

* echo
'color of tv2 is: ' . $tv2->getColor();//The color of tv2 is black
* echo
'
';

*

* //Replace tv2 and paint it white
* $tv2->setColor('white');
*

* echo
'color of tv2 is: ' . $tv2->getColor();//The color of tv2 is white
* echo
'
';

* echo
'color of tv1 is: ' . $tv1->getColor();//The color of tv1 is black


In the second line of this code, we use the clone keyword to copy tv1. Now we have a real copy of tv1, tv2. We still follow the previous method to check whether the copy is successful. We can see that we changed the color of tv2 to white, and the color of tv1 is still black, so our copy operation is successful.



__clone magic method

Now we consider the situation that each TV should have its own number. This number should be unique like our ID number, so when we copy a TV, we don’t want This number is also copied to avoid causing some trouble. One strategy we came up with is to clear the assigned TV numbers, and then reassign the numbers as needed.
Then the __clone magic method is specifically used to solve such problems. The __clone magic method will be triggered when the object is copied (that is, the clone operation). We modified the code of the TV class Television and added the number attribute and __clone method. The code is as follows.
PHP代码

* /**
* * TV
**/
* class Television
* {
*
* /**
* * TV number
**/
* protected
$_identity = 0;
*
* /**
* * screen height
**/
* protected
$_screenLength = 300;
*
* /**
* * screen width
**/
* protected
$_screenHight = 200;
*
* /**
* * TV appearance color
**/
* protected
$_color = 'black';
*
* /**
* * Return to TV appearance color
**/
* public
function getColor()
* {
* return
$this->_color;
* }
*
* /**
* * Set TV appearance color
**/
* public
function setColor($color)
* {
* $this->_color = (string)$color;
* return
$this;
* }
*
* /**
* * Return TV number
**/
* public
function getIdentity()
* {
* return
$this->_identity;
* }
*
* /**
* * Set TV number
**/
* public
function setIdentity($id)
* {
* $this->_identity = (int)$id;
* return
$this;
* }
*
* public
function __clone()
* {
* $this->setIdentity(0);
* }
* }


下面我们来复制这样的一个电视机对象。

PHP代码

* $tv1 = new Television();
* $tv1->setIdentity('111111');
* echo
'id of tv1 is ' . $tv1->getIdentity();//111111
* echo
'
';

*
* $tv2 = clone $tv1;
* echo
'id of tv2 is ' . $tv2->getIdentity();//0


我们生产了一台电视机tv1 , 并且设置它的编号为111111,然后我们用clone将tv1复制得到了tv2,这个时候__clone魔术方法被触发,此方法将直接作用与复制得到的对象tv2,我们在__clone方法中调用了setIdentity成员方法将tv2的_identity属性清空,以便我们后面对它进行重新编号。由此我们可以看到__clone魔术方法能让我们非常方便的在clone对象的时候做一些附加的操作。

clone操作的致命缺陷
clone真的能够达到理想的复制效果吗?在某些情况下,你应该会发现,clone操作并没有我们想象中的那么完美。我们将以上的电视机类修改一下,然后做测试。
每台电视机都会附带一个遥控器,所以我们将会有一个遥控器类,遥控器和电视机是一种“聚合”关系(相对与“组合”关系,是一种较弱的依赖关系,因为一般情况电视机就算没有遥控也能正常使用),现在我们的电视机对象应该都持有一个到遥控器对象的引用。Take a look at the code below
PHP code

* /**
* * TV
**/
* class Television
* {
*
* /**
* * TV number
**/
* protected
$_identity = 0;
*
* /**
* * screen height
**/
* protected
$_screenLength = 300;
*
* /**
* * screen width
**/
* protected
$_screenHight = 200;
*
* /**
* * TV appearance color
**/
* protected
$_color = 'black';
*
* /**
* * Remote control object
**/
* protected
$_control = null;
*
* /**
* * Load the remote control object in the constructor
**/
* public
function __construct()
* {
* $this->setControl(new Telecontrol());
* }
*
* /**
* * Set remote control object
**/
* public
function setControl(Telecontrol $control)
* {
* $this->_control = $control;
* return
$this;
* }
*
* /**
* * Returns the remote control object
**/
* public
function getControl()
* {
* return
$this->_control;
* }
*
* /**
* * Return to TV appearance color
**/
* public
function getColor()
* {
* return
$this->_color;
* }
*
* /**
* * Set TV appearance color
**/
* public
function setColor($color)
* {
* $this->_color = (string)$color;
* return
$this;
* }
*
* /**
* * Return TV number
**/
* public
function getIdentity()
* {
* return
$this->_identity;
* }
*
* /**
* * Set TV number
**/
* public
function setIdentity($id)
* {
* $this->_identity = (int)$id;
* return
$this;
* }
*
* public
function __clone()
* {
* $this->setIdentity(0);
* }
* }
*
*
* /**
* * Remote control category
**/
* class Telecontrol
* {
*
* }


Copy such a TV object below and observe the remote control object of the TV.

PHP code

* $tv1 = new Television();
* $tv2 = clone $tv1;
*
* $contr1 = $tv1->getControl(); //Get the remote control contr1 of tv1
* $contr2 = $tv2->getControl(); //Get the remote control contr2 of tv2
* echo
$tv1; //The object id of tv1 is #1
* echo
'
';

* echo
$contr1; //The object id of contr1 is #2
* echo
'
';

* echo
$tv2; //The object id of tv2 is #3
* echo
'
';

* echo
$contr2; //The object id of contr2 is #2


After copying, we check the object ID and copy tv2 from tv1 through the clone operation. The object IDs of tv1 and tv2 are 1 and 3 respectively. This means that tv1 and tv2 refer to two different TV objects, which is consistent with clone. The result of the operation. Then we obtained the remote control object contr1 of tv1 and the remote control object contr2 of tv2 respectively. By looking at their object IDs, we found that the object IDs of contr1 and contr2 are both 2, which indicates that they are references to the same object, that is It is obviously unreasonable to say that although we have copied tv2 from tv1, the remote control has not been copied. Each TV should be equipped with a remote control, and here tv2 and tv1 share a remote control.

It can be seen that the clone operation has such a big flaw: when using the clone operation to copy an object, when the copied object has references to other objects, the referenced objects will not be copied. However, this situation is very common. Nowadays, "synthesis/aggregation reuse" is mostly advocated to replace "inheritance reuse". "Synthesis" and "aggregation" are to let one object have a reference to another object, thereby reusing it. Use the method of the referenced object. We should consider this situation when using clone. So how should we solve such a defect when cloning an object? Maybe you quickly thought of the __clone magic method mentioned earlier, which is indeed a solution.

Option 1: Use __clone magic method to make up for it
We have already introduced the use of the __clone magic method. We can re-reference the references of other objects in the copied object to a new object in the __clone method. Let’s take a look at the modified __clone() magic method:

[size=+0][size=+0]PHP code

* [size=+0][size=+0]public
function __clone()
* {
* $this->setIdentity(0);
* //Reset a remote control object
* $this->setControl(new Telecontrol());
* }


In line 04, we reset a remote control for the copied TV object. We check the object ID according to the previous method and can find that the remote controls of the two TVs have different object IDs, so our problem is solved.

But this method is probably not very good. If the copied object has multiple references to other objects, we must reset them one by one in the __clone method. What’s worse is if the class of the copied object is changed by If provided by a third party, we cannot modify the code, so the copy operation will basically not be completed smoothly.
We use clone to copy objects. This kind of copy is called "shallow copy": all variables of the copied object contain the same values ​​as the original object, and all references to other objects still point to the original object. That is, a shallow copy only copies the object in question, not the objects it refers to. Compared with "shallow copy", of course there is also a "deep copy": all variables of the copied object contain the same values ​​as the original object, except those variables that refer to other objects. In other words, deep copy copies all the objects referenced by the object to be copied. Deep copying requires deciding how deep to go, which is a problem that is not easy to determine. In addition, circular reference problems may occur, which must be handled carefully. Our option 2 will be a deep copy solution.

Option 2: Use serialization for deep copy
PHP has serialize and unserialize functions. We only need to use serialize() to write an object to a stream, and then read the object back from the stream, then the object will be copied. In the Java language, this process is called "refrigeration" and "thawing". Below we will test this method:
[size=+0][size=+0]PHP code

* [size=+0][size=+0]$tv1 = new Television();
* $tv2 = unserialize(serialize($tv1));//Serialize and then deserialize
*

* $contr1 = $tv1->getControl(); //Get the remote control contr1 of tv1
* $contr2 = $tv2->getControl(); //Get the remote control contr2 of tv2
*

* echo
$tv1; //The object id of tv1 is #1
* echo
'
';

* echo
$contr1; //The object id of contr1 is #2
* echo
'
';

* echo
$tv2; //The object id of tv2 is #4
* echo
'
';

* echo
$contr2; //The object id of contr2 is #5


We can see the output, tv1 and tv2 have different remote controls. This is much more convenient than Option 1. Serialization is a recursive process. We don't need to care about how many objects are referenced within the object and how many layers of objects are referenced. We can completely copy it. Note that when using this solution, we cannot trigger the __clone magic method to complete some additional operations. Of course, we can perform a clone operation again after deep copying to trigger the __clone magic method, but it will have a small impact on efficiency. In addition, this solution will trigger the __sleep and __wakeup magic methods of the copied object and all referenced objects, so these situations need to be considered.



Summary
Different object copying methods have different effects. We should consider which method to use and how to improve the copying method based on specific application requirements. The object-oriented features of PHP5 are relatively close to JAVA. I believe we can learn a lot of valuable experience from JAVA.
clone


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
11 Best PHP URL Shortener Scripts (Free and Premium)11 Best PHP URL Shortener Scripts (Free and Premium)Mar 03, 2025 am 10:49 AM

Long URLs, often cluttered with keywords and tracking parameters, can deter visitors. A URL shortening script offers a solution, creating concise links ideal for social media and other platforms. These scripts are valuable for individual websites a

Introduction to the Instagram APIIntroduction to the Instagram APIMar 02, 2025 am 09:32 AM

Following its high-profile acquisition by Facebook in 2012, Instagram adopted two sets of APIs for third-party use. These are the Instagram Graph API and the Instagram Basic Display API.As a developer building an app that requires information from a

Working with Flash Session Data in LaravelWorking with Flash Session Data in LaravelMar 12, 2025 pm 05:08 PM

Laravel simplifies handling temporary session data using its intuitive flash methods. This is perfect for displaying brief messages, alerts, or notifications within your application. Data persists only for the subsequent request by default: $request-

Build a React App With a Laravel Back End: Part 2, ReactBuild a React App With a Laravel Back End: Part 2, ReactMar 04, 2025 am 09:33 AM

This is the second and final part of the series on building a React application with a Laravel back-end. In the first part of the series, we created a RESTful API using Laravel for a basic product-listing application. In this tutorial, we will be dev

Simplified HTTP Response Mocking in Laravel TestsSimplified HTTP Response Mocking in Laravel TestsMar 12, 2025 pm 05:09 PM

Laravel provides concise HTTP response simulation syntax, simplifying HTTP interaction testing. This approach significantly reduces code redundancy while making your test simulation more intuitive. The basic implementation provides a variety of response type shortcuts: use Illuminate\Support\Facades\Http; Http::fake([ 'google.com' => 'Hello World', 'github.com' => ['foo' => 'bar'], 'forge.laravel.com' =>

cURL in PHP: How to Use the PHP cURL Extension in REST APIscURL in PHP: How to Use the PHP cURL Extension in REST APIsMar 14, 2025 am 11:42 AM

The PHP Client URL (cURL) extension is a powerful tool for developers, enabling seamless interaction with remote servers and REST APIs. By leveraging libcurl, a well-respected multi-protocol file transfer library, PHP cURL facilitates efficient execution of various network protocols, including HTTP, HTTPS, and FTP. This extension offers granular control over HTTP requests, supports multiple concurrent operations, and provides built-in security features.

12 Best PHP Chat Scripts on CodeCanyon12 Best PHP Chat Scripts on CodeCanyonMar 13, 2025 pm 12:08 PM

Do you want to provide real-time, instant solutions to your customers' most pressing problems? Live chat lets you have real-time conversations with customers and resolve their problems instantly. It allows you to provide faster service to your custom

Announcement of 2025 PHP Situation SurveyAnnouncement of 2025 PHP Situation SurveyMar 03, 2025 pm 04:20 PM

The 2025 PHP Landscape Survey investigates current PHP development trends. It explores framework usage, deployment methods, and challenges, aiming to provide insights for developers and businesses. The survey anticipates growth in modern PHP versio

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version