In this code
<?php
$object1 = new User();
$object1->name = "Alice";
$object2 = clone $object1;
$object2->name = "Amy";
echo "object1 name = " . $object1->name . "<br>";
echo "object2 name = " . $object2->name;
class User
{
public $name;
}
?>
what's the advantage of using clone
rather than just new
?
Is it such that we get all the same values for the attributes of object1
in object2
except for the name
which we define newly?
In this specific situation there will be no difference. There would be a difference if the object had other properties (they would get reset if creating a new instance instead of cloning).
There are also other situations where clone
can be appropriate:
clone
will copy all the property values rather than have them reset to the default. Useful if you have a query builder class, for example, and wish for two queries to be near-identical but for one or two small differences. You build the query up to the point of departure, clone it, and then use one one way and the other another.
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