Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use of __clone in PHP?

Tags:

I have a class a and instantiated it using new

$obja = new a;

I know the difference between the below two lines

$obja2 = $ojba;
$obja2 = clone $obja;

But even if you declare or not declare __clone in the class a the first line $obja2 refer to $obja memory space and second line creates a copy of the $obja. Till here it is clear to me.

Then why php is having a magic method __clone? Is it only for executing a set of codes which is written inside __clone while we use $obja2 = clone $obja;

Somebody please help to get a better idea of it.

like image 348
zamil Avatar asked Dec 20 '12 11:12

zamil


People also ask

What is clone () method?

clone() method in JavaJava provides an assignment operator to copy the values but no operator to copy the object. Object class has a clone method which can be used to copy the values of an object without any side-effect.

Which magic function is used to clone an object?

The __clone() magic method is used to clone a class using a same new instance. If you notice closely, when we create a new object of class likeso, $class = new DevPeel(); a new object created of a classes and includes a index flag with the object.

Which is correct syntax of creating clone object?

An object copy is created by using the clone keyword (which calls the object's __clone() method if possible). $copy_of_object = clone $object; When an object is cloned, PHP will perform a shallow copy of all of the object's properties. Any properties that are references to other variables will remain references.

What is deep copy and shallow copy in PHP?

Deep copies duplicate everything. A deep copy, meaning that fields are de-referenced: rather than references to objects being copied, new copy objects are created for any referenced objects, and references to these placed in new object. Shallow copies duplicate as little as possible.


1 Answers

void __clone ( void )

Once the cloning is complete, if a __clone() method is defined, then the newly created object's __clone() method will be called, to allow any necessary properties that need to be changed.

http://php.net/manual/en/language.oop5.cloning.php#object.clone

So yes, it's a callback after the clone operation has finished. Nothing more, nothing less.

like image 106
deceze Avatar answered Sep 24 '22 13:09

deceze