


What is the difference between deep copy and shallow copy in php
The difference between deep copy and shallow copy in PHP: 1. Deep copy is a complete copy when assigning, while shallow copy is just a reference assignment, which is equivalent to taking an alias; 2. If deep copy makes a Changes will not affect the other, while shallow copy modifications to one will affect the other.
The operating environment of this tutorial: windows10 system, PHP7.1 version, DELL G3 computer
The difference between deep copy and shallow copy in php is What
Let’s first talk about the popular understanding of deep copy and shallow copy
Deep copy: the value during assignment is completely copied, complete copy, making changes to one of them will not affect the other
Shallow copy: When assigning, reference assignment is equivalent to taking an alias. Modifications to one of them will affect the other
In PHP, when = is assigned, ordinary objects are deep copies, but for objects, they are shallow copies. In other words, the assignment of an object is a reference assignment. (When an object is passed as a parameter, it is also passed by reference, regardless of whether there is an ampersand in front of the parameter when the function is defined)
In php4, the = assignment of the object is to implement a copy, which has many problems. We may make many copies.
In PHP5, the = assignment and transfer of objects are both references. To implement a copy, PHP provides the clone function implementation.
clone makes a complete copy. But when cloning, we may not want to copy all the contents of the source object, then we can use __clone to operate.
In __clone(), we can perform some operations. Note that these operations, that is, the __clone function operates on the copied copy object
<?php //普通对象赋值,深拷贝,完全值复制 $m = 1; $n = $m; $n = 2; echo $m;//值复制,对新对象的改变不会对m作出改变,输出 1.深拷贝 echo PHP_EOL; /*==================*/ //对象赋值,浅拷贝,引用赋值 class Test{ public $a=1; } $m = new Test(); $n = $m;//引用赋值 $m->a = 2;//修改m,n也随之改变 echo $n->a;//输出2,浅拷贝 echo PHP_EOL; ?>
Since the object is referenced during assignment, in order to realize value copying, PHP provides the clone function to copy the object.
But there is a problem with the clone function. When an object is cloned, the ordinary attributes of the original object can be copied by value, but when the object attributes of the source object are assigned, they are still reference assignments and shallow copies.
<?php class Test{ public $a=1; } class TestOne{ public $b=1; public $obj; //包含了一个对象属性,clone时,它会是浅拷贝 public function __construct(){ $this->obj = new Test(); } } $m = new TestOne(); $n = $m;//这是完全的浅拷贝,无论普通属性还是对象属性 $p = clone $m; //普通属性实现了深拷贝,改变普通属性b,不会对源对象有影响 $p->b = 2; echo $m->b;//输出原来的1 echo PHP_EOL; //对象属性是浅拷贝,改变对象属性中的a,源对象m中的对象属性中a也改变 $p->obj->a = 3; echo $m->obj->a;//输出3,随新对象改变 ?>
To achieve a true deep copy of an object, there are two methods:
Write the clone function: as follows
<?php class Test{ public $a=1; } class TestOne{ public $b=1; public $obj; //包含了一个对象属性,clone时,它会是浅拷贝 public function __construct(){ $this->obj = new Test(); } //方法一:重写clone函数 public function __clone(){ $this->obj = clone $this->obj; } } $m = new TestOne(); $n = clone $m; $n->b = 2; echo $m->b;//输出原来的1 echo PHP_EOL; //可以看到,普通属性实现了深拷贝,改变普通属性b,不会对源对象有影响 //由于改写了clone函数,现在对象属性也实现了真正的深拷贝,对新对象的改变,不会影响源对象 $n->obj->a = 3; echo $m->obj->a;//输出1,不随新对象改变,还是保持了原来的属性 ?>
It is not convenient to rewrite the __clone() function. And you have to put all the object attributes in this class in __clone() in each class - clone
The second method is to use serialization and deserialization. This method realizes the object Deep copy is simple and does not need to modify the class
<?php class Test{ public $a=1; } class TestOne{ public $b=1; public $obj; //包含了一个对象属性,clone时,它会是浅拷贝 public function __construct(){ $this->obj = new Test(); } } $m = new TestOne(); //方法二,序列化反序列化实现对象深拷贝 $n = serialize($m); $n = unserialize($n); $n->b = 2; echo $m->b;//输出原来的1 echo PHP_EOL; //可以看到,普通属性实现了深拷贝,改变普通属性b,不会对源对象有影响 $n->obj->a = 3; echo $m->obj->a;//输出1,不随新对象改变,还是保持了原来的属性,可以看到,序列化和反序列化可以实现对象的深拷贝 ?>
There is also a third method, which is actually similar to the second method. json_encode and then json_decode to achieve assignment
Recommended learning: "PHP Video tutorial》
The above is the detailed content of What is the difference between deep copy and shallow copy in php. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7
