Object copy versus clone in PHP

感情迁移 提交于 2019-11-28 19:13:33

Yes, that's normal. Objects are always "assigned" by reference in PHP5. To actually make a copy of an object, you need to clone it.

To be more correct though, let me quote the manual:

As of PHP5, an object variable doesn't contain the object itself as value anymore. It only contains an object identifier which allows object accessors to find the actual object. When an object is sent by argument, returned or assigned to another variable, the different variables are not aliases: they hold a copy of the identifier, which points to the same object.

hakre

That's normal and I won't consider this unintuitive (for object instances):

$object1 = new stdClass();

Assigns a new object instance to $object1.

$object2 = $object1;

Assigns the object instance to $object2.

$object3 = clone $object1;

Assigns an new object instance cloned from an existing object instance to $object3.

If it would not be that way, each time you need to pass a concrete object instance, you would need to pass it by reference. That's burdensome at least but PHP did so in version 4 (compare zend.ze1_compatibility_mode core ). That was not useful.

Cloning allows the object to specify how it get's copied.

object copy vs object clone

class test{
public $name;
public $addr;
}
// i create a object $ob
$ob=new test();

// object copy 

$ob2=$ob;

// in object copy both object will represent same memory address 
// example 
$ob->name='pankaj raghuwanshi';

// i am printing second object
echo $ob2->name;
// output is : pankaj raghuwanshi

// another example 

$ob2->name='raghuwanshi pankaj';
echo $ob->name;
// output is :  raghuwanshi pankaj

// it means in copy of object original and copy object share same memory place

now clone of an object

$ob1=clone $ob;

echo $ob1->name;  // output is :  raghuwanshi pankaj
echo $ob->name;   // output is :  raghuwanshi pankaj

 $ob1->name='PHP Clone';
 $ob->name='PHP Obj';

echo $ob1->name;  // output is :  PHP Clone
echo $ob->name;   // output is :  PHP Obj

// on the base of these output we can say both object have their own memory space 
// both are independent 

Objects in php5 are essentially pointers, that is, an object variable contains only an address of the object data located somewhere else. An assignment $obj1 = $obj2 only copies this address and doesn't touch the data itself. This may indeed appear counterintuitive, but in fact it's quite practical, because you only rarely need to have two copies of the object. I wish php arrays used the same semantics.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!