search
HomeBackend DevelopmentPHP TutorialLearn about PHP object cloning clone

Learn about PHP object cloning clone

Jun 09, 2018 pm 02:42 PM
clonephp

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 = &#39;fdipzone&#39;;
		$this->age = &#39;30&#39;;
	}
	public function __clone(){
		$this->name = &#39;xfdipzone&#39;;
		$this->age = &#39;29&#39;;
	}
}
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 &#39;<pre class="brush:php;toolbar:false">&#39;;
echo &#39;obj<br>&#39;;
var_dump($obj);
echo &#39;<br>obj2<br>&#39;;
var_dump($obj2);
echo &#39;ok&#39;;
echo &#39;
'; ?>

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 = &#39;OK&#39;;
	}
	public function __clone(){
		$this->num = 2;	
	}
}
$obj = new myclass();
$obj->num = 1;
echo &#39;print obj values<br>&#39;;
var_dump($obj);
echo &#39;<br><br>&#39;;
$obj2 = clone $obj;
echo &#39;clone obj to obj2<br>&#39;;
echo &#39;obj->num:&#39;.$obj->num.&#39;<br>&#39;;
echo &#39;obj->msg:&#39;.$obj->msg.&#39;<br>&#39;;
echo &#39;obj2->num:&#39;.$obj2->num.&#39;<br>&#39;;
echo &#39;obj2->msg:&#39;.$obj2->msg.&#39;<br><br>&#39;;
$obj2->num = 3;
$obj2->msg = &#39;Yes&#39;;
echo &#39;set obj2->num=3, obj2->msg=Yes<br>&#39;;
echo &#39;obj->num:&#39;.$obj->num.&#39;<br>&#39;;
echo &#39;obj->msg:&#39;.$obj->msg.&#39;<br>&#39;;
echo &#39;obj2->num:&#39;.$obj2->num.&#39;<br>&#39;;
echo &#39;obj2->msg:&#39;.$obj2->msg.&#39;<br><br>&#39;;
?>

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!

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
What is the difference between unset() and session_destroy()?What is the difference between unset() and session_destroy()?May 04, 2025 am 12:19 AM

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

What is sticky sessions (session affinity) in the context of load balancing?What is sticky sessions (session affinity) in the context of load balancing?May 04, 2025 am 12:16 AM

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

What are the different session save handlers available in PHP?What are the different session save handlers available in PHP?May 04, 2025 am 12:14 AM

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

What is a session in PHP, and why are they used?What is a session in PHP, and why are they used?May 04, 2025 am 12:12 AM

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.

Explain the lifecycle of a PHP session.Explain the lifecycle of a PHP session.May 04, 2025 am 12:04 AM

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

What is the difference between absolute and idle session timeouts?What is the difference between absolute and idle session timeouts?May 03, 2025 am 12:21 AM

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.

What steps would you take if sessions aren't working on your server?What steps would you take if sessions aren't working on your server?May 03, 2025 am 12:19 AM

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.

What is the significance of the session_start() function?What is the significance of the session_start() function?May 03, 2025 am 12:18 AM

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

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

Video Face Swap

Video Face Swap

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

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

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

SublimeText3 Linux new version

SublimeText3 Linux latest version

EditPlus Chinese cracked version

EditPlus Chinese cracked version

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor