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.
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With