What is the advantage of cloning over creating a new object in PHP?

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 is the advantage of using clone , not just new ? Is it that we get all the same values ​​for the attributes of object1 in object2 , with the exception of name , which we redefine?

+4
source share
3 answers

In this particular situation there will be no difference. It would be a difference if the object had other properties (they could get reset by creating a new instance instead of cloning).

There are other situations where clone may be appropriate:

  • If the object class does not have a constructor available to you
  • If the class of the object has a constructor, but you do not know what values ​​you should pass to it; in general, if you don’t know how you would build a duplicate object
  • If unwanted side effects occur when creating a new object
  • If the object has an internal state, and you do not know how to go from the state of β€œjust built” to the state of the instance that you already have.
+9
source

clone will copy all property values, and will not have a reset value by default. It is useful if you have a query builder class, for example, and it is desirable that the two queries are almost identical, but for one or two small differences. You build the request to the point of departure, clone it, and then use one method and another.

+2
source

In this case, they are not, because this is a very bad excuse for the object.

However, imagine that you are creating a game where each class represents a type of object in the game. One such object may be a ball that bounces. In this case, new Ball() will create a new ball in its original position, and it will bounce along the first. However, clone $ball1 will duplicate the current ball in its actual position.

+1
source

All Articles