note 117616 deleted from language.oop5.cloning by cmb

From: Date: Sun, 10 Jul 2016 20:07:37 +0000
Subject: note 117616 deleted from language.oop5.cloning by cmb
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-205949@lists.php.net to get a copy of this message
Note Submitter: dennis ---- I had some trouble with cloning an array with objects in another object. But I found a function on the internet that was very helpful: function array_clone( array $array ) { $result = array(); foreach( $array as $key => $val ) { if( is_array( $val ) ) { $result[$key] = arrayCopy( $val ); } elseif ( is_object( $val ) ) { $result[$key] = clone $val; } else { $result[$key] = $val; } } return $result; } //== my test case: class Employee { public $sName = ''; } class EmployeesContainer { private $arrObjects = array(); public function __clone() { //try to comment out the line below, you will see the out differs $this->arrObjects = array_clone($this->arrObjects); } public function add(Employee $objEmployee) { $this->arrObjects[] = $objEmployee; } public function getInternalArray() { return $this->arrObjects; } } $objContainerOriginal = new EmployeesContainer(); $objEmpl1 = new Employee(); $objEmpl1->sName = 'erny'; $objContainerOriginal->add($objEmpl1); $objEmpl2 = new Employee(); $objEmpl2->sName = 'bert'; $objContainerOriginal->add($objEmpl2); $objContainerClone = clone $objContainerOriginal; if ($objContainerClone->getInternalArray()[1] === $objEmpl2) echo 'SAME object: '.$objContainerClone->getInternalArray()[0]->sName.' <-> '.$objEmpl1->sName; else echo 'OTHER object: '.$objContainerClone->getInternalArray()[0]->sName.' <-> '.$objEmpl1->sName;

« previous php.notes (#205949) next »