I thought PHP = is a simple assignment of values. For instance:
$x = 1; $a = $x; $b = $x; $a++; echo $a; echo $b;
Produces 21 , as expected. However, the code below behaves differently than I expected. I basically tried to assign the "same" value to many variables:
class X { public $val = 0; public function doSomething() { $this->val = "hi"; } } function someFunction() { $template = array('non_object' => 0, 'object' => new X()); $a = $template; $b = $template;
It produces:
array(2) { ["non_object"]=> int(0) ["object"]=> object(X)#1 (1) { ["val"]=> string(2) "hi" } } array(2) { ["non_object"]=> int(0) ["object"]=> object(X)#1 (1) { ["val"]=> string(2) "hi" } }
As you can see, the object property in array A has changed as expected, but also changed in array B
You can check the code here: http://sandbox.onlinephpfunctions.com/code/bff611fc9854b777114d38a3b4c60d524fdf2e19
How can I assign one value to many PHP variables and manipulate them without having them in this state of "quantum entanglement" and without copying?
source share