Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the advantage of `clone` over instantiating a new object in PHP?

Tags:

object

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'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?

like image 471
TMOTTM Avatar asked Mar 29 '13 23:03

TMOTTM


2 Answers

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:

  • If the class of the object does not have a constructor that is accessible to you
  • If the class of the object does have a constructor, but you don't know what values you should pass to it; in general, if you don't know how you would construct a duplicate object
  • If constructing a new object has side effects that are undesirable
  • If the object has internal state and you don't know how to move from a "freshly constructed" state to that of the instance you already have
like image 59
Jon Avatar answered Oct 11 '22 13:10

Jon


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.

like image 32
MichaelRushton Avatar answered Oct 11 '22 13:10

MichaelRushton