tags:

views:

53

answers:

3

How can you modify the copy of an object during a clone operation?

A: 
$clone = clone $object;
modify($clone);

Though true, this is after the clone operation; I have no clue how to do it during the operation (if it's even possible)

azatoth
+3  A: 

Use __clone(): http://www.php.net/manual/en/language.oop5.cloning.php

Wrikken
+1  A: 
class MyClass {

    private $myArray = array();

    public function pushSomethingToArray($var) {
        array_push($this->myArray, $var);
    }   //  function pushSomethingToArray()

    public function getArray() {
        return $this->myArray;
    }   //  function getArray()

    public function __clone()
    {
        //  clear array
        $this->myArray = array();
    }   //  function __clone()
}

$myObj = new MyClass();
$myObj->pushSomethingToArray('blue');
$myObj->pushSomethingToArray('orange');

$myObjClone = clone $myObj;
$myObjClone->pushSomethingToArray('red');

var_dump($myObj->getArray());
echo '<br />';
var_dump($myObjClone->getArray());
Mark Baker