php Object copying is to copy the reference address of the object, so when using $objA = $objB, $objA and $objB will point to the same memory address. When $objA changes, $objB is also affected.
If we want the $objA object to be copied into an $objB object, any changes to $objA after copying will not affect $objB. That is, $objA and $objB are two independent objects, but the initial value of $objB is created by $objA. A more efficient way is to use the clone() method.
$objB = clone $objA;
The value of $objB is the instance changed by the clone() method in the $objA instance object based on $objA.
When the object is copied, the references in all attributes remain unchanged and point to the original variables. If the __clone() method is defined, the __clone( ) method will be called and can be used to modify the value of the attribute.
Example 1: clone object
<?php class subclass{ private $name; private $age; public function __construct(){ $this->name = 'fdipzone'; $this->age = '30'; } public function __clone(){ $this->name = 'xfdipzone'; $this->age = '29'; } } class myclass{ public $p1; public $p2; public function __construct(){ } public function __clone(){ $this->p1 = clone $this->p1; } } $obj = new myclass(); $obj->p1 = new subclass(); $obj->p2 = new subclass(); $obj2 = clone $obj; echo '<pre class="brush:php;toolbar:false">'; echo 'obj<br>'; var_dump($obj); echo '<br>obj2<br>'; var_dump($obj2); echo 'ok'; echo ''; ?>
The above example will output:
obj object(myclass)#1 (2) { ["p1"]=> object(subclass)#2 (2) { ["name":"subclass":private]=> string(8) "fdipzone" ["age":"subclass":private]=> string(2) "30" } ["p2"]=> object(subclass)#3 (2) { ["name":"subclass":private]=> string(8) "fdipzone" ["age":"subclass":private]=> string(2) "30" } } obj2 object(myclass)#4 (2) { ["p1"]=> object(subclass)#5 (2) { ["name":"subclass":private]=> string(9) "xfdipzone" ["age":"subclass":private]=> string(2) "29" } ["p2"]=> object(subclass)#3 (2) { ["name":"subclass":private]=> string(8) "fdipzone" ["age":"subclass":private]=> string(2) "30" } }
As you can see, $obj2 clone $obj, $obj->p1 clone $obj->p1, and the __clone() method is executed. In the __clone method, the name and age attributes of p1 are modified, so the name and age of p1 change. Since p2 has not executed the clone() method, the properties of the newly copied $obj2->p2 are the same as $obj->p2.
Example 2: Clone the object, but some attribute references remain unchanged.
<?php class myclass{ public $num = null; public $msg = null; public function __construct(){ $this->num = & $this->num; $this->msg = 'OK'; } public function __clone(){ $this->num = 2; } } $obj = new myclass(); $obj->num = 1; echo 'print obj values<br>'; var_dump($obj); echo '<br><br>'; $obj2 = clone $obj; echo 'clone obj to obj2<br>'; echo 'obj->num:'.$obj->num.'<br>'; echo 'obj->msg:'.$obj->msg.'<br>'; echo 'obj2->num:'.$obj2->num.'<br>'; echo 'obj2->msg:'.$obj2->msg.'<br><br>'; $obj2->num = 3; $obj2->msg = 'Yes'; echo 'set obj2->num=3, obj2->msg=Yes<br>'; echo 'obj->num:'.$obj->num.'<br>'; echo 'obj->msg:'.$obj->msg.'<br>'; echo 'obj2->num:'.$obj2->num.'<br>'; echo 'obj2->msg:'.$obj2->msg.'<br><br>'; ?>
The above example will output:
print obj values object(myclass)#1 (2) { ["num"]=> &int(1) ["msg"]=> string(2) "OK" } clone obj to obj2 obj->num:2 obj->msg:OK obj2->num:2 obj2->msg:OK set obj2->num=3, obj2->msg=Yes obj->num:3 obj->msg:OK obj2->num:3 obj2->msg:Yes
Because $this->num = &$this-> ;num, so after clone(), $this->num of the new object refers to the memory address of the old object. Therefore, if the properties of the old object change, the properties of the new object will also change, so that the references to certain properties remain unchanged.
And $this->msg is not an address reference, so if the msg of the new object changes, it will not affect the old object.
Note: $this->num = & $this->num When using object attribute address reference, you cannot echo/print this attribute before cloning , otherwise the address reference will be invalid.
In the above example, if $obj2 = clone $obj is added before, echo $obj->num; will make the address reference The actual effect is that if $obj2->num changes, $obj->num will not change.
This article introduces the related content of PHP object cloning clone. For more related content, please pay attention to PHP Chinese website.
Related recommendations:
Related operations on mysql general log
Introduction to the php Cookies operation class
Introduction to PHP password generation class
The above is the detailed content of Learn about PHP object cloning clone. For more information, please follow other related articles on the PHP Chinese website!

Thedifferencebetweenunset()andsession_destroy()isthatunset()clearsspecificsessionvariableswhilekeepingthesessionactive,whereassession_destroy()terminatestheentiresession.1)Useunset()toremovespecificsessionvariableswithoutaffectingthesession'soveralls

Stickysessionsensureuserrequestsareroutedtothesameserverforsessiondataconsistency.1)SessionIdentificationassignsuserstoserversusingcookiesorURLmodifications.2)ConsistentRoutingdirectssubsequentrequeststothesameserver.3)LoadBalancingdistributesnewuser

PHPoffersvarioussessionsavehandlers:1)Files:Default,simplebutmaybottleneckonhigh-trafficsites.2)Memcached:High-performance,idealforspeed-criticalapplications.3)Redis:SimilartoMemcached,withaddedpersistence.4)Databases:Offerscontrol,usefulforintegrati

Session in PHP is a mechanism for saving user data on the server side to maintain state between multiple requests. Specifically, 1) the session is started by the session_start() function, and data is stored and read through the $_SESSION super global array; 2) the session data is stored in the server's temporary files by default, but can be optimized through database or memory storage; 3) the session can be used to realize user login status tracking and shopping cart management functions; 4) Pay attention to the secure transmission and performance optimization of the session to ensure the security and efficiency of the application.

PHPsessionsstartwithsession_start(),whichgeneratesauniqueIDandcreatesaserverfile;theypersistacrossrequestsandcanbemanuallyendedwithsession_destroy().1)Sessionsbeginwhensession_start()iscalled,creatingauniqueIDandserverfile.2)Theycontinueasdataisloade

Absolute session timeout starts at the time of session creation, while an idle session timeout starts at the time of user's no operation. Absolute session timeout is suitable for scenarios where strict control of the session life cycle is required, such as financial applications; idle session timeout is suitable for applications that want users to keep their session active for a long time, such as social media.

The server session failure can be solved through the following steps: 1. Check the server configuration to ensure that the session is set correctly. 2. Verify client cookies, confirm that the browser supports it and send it correctly. 3. Check session storage services, such as Redis, to ensure that they are running normally. 4. Review the application code to ensure the correct session logic. Through these steps, conversation problems can be effectively diagnosed and repaired and user experience can be improved.

session_start()iscrucialinPHPformanagingusersessions.1)Itinitiatesanewsessionifnoneexists,2)resumesanexistingsession,and3)setsasessioncookieforcontinuityacrossrequests,enablingapplicationslikeuserauthenticationandpersonalizedcontent.


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

Atom editor mac version download
The most popular open source editor

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 Linux new version
SublimeText3 Linux latest version

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

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