0

Here's the code

class Foo {
   public $a;
}

$arr = [];

$foo = new Foo();
$foo->a = 1;

$arr[0] = $foo;
$arr[0]->a = 2;

echo $foo->a;

The result is 2 in my testing. However I am not sure whether this behavior is guaranteed or the behavior is random and/or will change based on the state of optimizer/version/memory usage/associative or not/...

Is it guaranteed?

Note: the reason I am having this question is the following code will output 1

$arr = [];
$foo = 1;
$arr[0] = $foo;
$arr[0] = 2;
echo $foo;
cr001
  • 655
  • 4
  • 16

1 Answers1

0

As those $foo and $arr are pointing to the same position at memory, so any changing from $arr will affect at $foo too. in fact : $arr[0] === $foo

if you want to clone a var from $foo you must test this:

$arr[0] = clone $foo;

so any modification in $arr wont affect at $foo and vice versa.