Php clone keyword

Possible duplicate:
What is cloning of objects in php?

I am exploring an existing structure that reuses the clone keyword, but not sure if this is a good idea? I really don't understand the need to use the clone keyword.

for example look at this coding

ie

  public function getStartDate ()
  {
    return clone $this->startDate;
  }

for me, this function should be as below, I do not see the need for a clone.

  public function getStartDate ()
  {
    return $this->startDate;
  }
+5
source share
3 answers

The reason for using the clone is that when working with an object, PHP always returns the object as a link, and not as a copy.

That's why when passing an object to a function, you don’t need to specify it and (link):

function doSomethingWithObject(MyObject $object) { // it is same as MyObject &object
   ...
}

, , clone , php :

class Obj {
    public $obj;
    public function __construct() {
        $this->obj = new stdClass();
        $this->obj->prop = 1; // set a public property
    }
    function getObj(){
        return $this->obj; // it returns a reference
    }
}

$obj = new Obj();

$a = $obj->obj; // get as public property (it is reference)
$b = $obj->getObj(); // get as return of method (it is also a reference)
$b->prop = 7;
var_dump($a === $b); // (boolean) true
var_dump($a->prop, $b->prop, $obj->obj->prop); // int(7), int(7), int(7)
// changing $b->prop didn't actually change other two object, since both $a and $b are just references to $obj->obj

$c = clone $a;
$c->prop = -3;
var_dump($a === $c); // (boolean) false
var_dump($a->prop, $c->prop, $obj->obj->prop); // int(7), int(-3), int(7)
// since $c is completely new copy of object $obj->obj and not a reference to it, changing prop value in $c does not affect $a, $b nor $obj->obj!
+7

, startDate .

. clone $this->startDate - . , , . - , startDate .

- . , - . , - startDate.

, , .

.

+3

even though it is fully explained in another question (thanks for pointing this out @gerald)

just a quick answer:

without cloning, the function returns a reference to the startDate object. A copy is returned with the clone.

if the returned object is changed later, it only changes the copy, not the original, which can be used elsewhere.

0
source

All Articles