note 117616 added to language.oop5.cloning
| From: | dennis | Date: | Wed, 08 Jul 2015 22:45:18 +0000 |
| Subject: | note 117616 added to language.oop5.cloning | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-203065@lists.php.net to get a copy of this message | ||
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;
----
Server IP: 216.235.13.26
Probable Submitter: 195.240.127.167
----
Manual Page -- http://php.net/manual/en/language.oop5.cloning.php
Edit -- https://master.php.net/note/edit/117616
Del: integrated -- https://master.php.net/note/delete/117616/integrated
Del: useless -- https://master.php.net/note/delete/117616/useless
Del: bad code -- https://master.php.net/note/delete/117616/bad+code
Del: spam -- https://master.php.net/note/delete/117616/spam
Del: non-english -- https://master.php.net/note/delete/117616/non-english
Del: in docs -- https://master.php.net/note/delete/117616/in+docs
Del: other reasons-- https://master.php.net/note/delete/117616
Reject -- https://master.php.net/note/reject/117616
Search -- https://master.php.net/manage/user-notes.php