I'm puzzled by the behaviour in the following example. I stumbled over this in a project and it took me hours to narrow the problem down to a simple example. So this is my simple test class:
<?php
class Foo {
public $sess = [['name' => 'John']];
public function info() {
$this->runTest();
echo $this->sess[0]['name'];
}
private function runTest() {
$localSess = &$this->sess[0];
$this->sessTest();
}
private function sessTest() {
$sessCopy = $this->sess;
$this->sess[0]['name'] = 'Bob';
$this->sess = $sessCopy;
}
}
$myFoo = new Foo;
$myFoo->info();
The unexpected resulting output is:
Bob
If $localSess is just a simple assignment and not a reference, the output is (as expected): John
I don't understand what's going on here. Since the class property $sess is an array and not an object, the assignment to $sessCopy should be a simple copy. But if you print the content of $sessCopy right after modifying $this->sess, it will contain the changed value for 'name'. So it seems as if $sessCopy were a reference after all? But only if $localSess in the calling method is a reference. Why should that even matter? BTW, if $localSess is a reference to the whole array of the class property and not just to its first index, everything works as expected.
Can someone please shed some light on this? If the mere existence of a variable reference in one function can influence the content of a local variable (not a reference!) in another function, then that seems dangerous and scary.