oop - Object assignment is creating a reference in PHP
one text
Solution:
The problem is in the way the PHP uses arrays. Array assignment by reference only works if both the argument and the lvalue are references to arrays. If an object is passed in, it will be copied and a reference to it will be set in both places. The subsequent reassignment of the lvalue will not have any effect on the original array.
Referencing an existing array and then copying it using clone can work around this. The example below shows how this can be done, but you could also use a factory or some other means to create a new array that has references to all of the existing elements (by calling get_object_vars() on each).
<?php
function getNewList(TestBase $ref) : array
{
$newlist = [3 => clone $ref, 5 => clone $ref];
$newlist[3]->SetTest(3);
$newlist[5]->SetTest(5);
return $newlist;
}
//$ref = clone $listOfTest[4];
$ref = &$listOfTest[4];
var_dump($ref); // TestBase Object (1) (2) { ["m_test"]=> int(5) }
//$newList = getNewList($ref);
foreach ($listOfTest as &$test)
{
echo "before: ".$test->GetTest().'<br>'; // 2, 4, 6 in output here!
var_dump($test); // TestBase Object (1) (2) { ["m_test"]=> int(4) }
echo "after: ".$test->GetTest().'<br>'; // 2, 4, 6 in output here!
var_dump($test); // TestBase Object (1) (2) { ["m_test"]=> int(4) }
}
?>
Source