variable losing reference after being set in function
Description
I ran into the below scenario, which might be correct, but it wasn't something I expected, and I wanted to make sure it's the correct behavior.
In the below scenario, why do $a and $b lose their references, but $c retains the reference? I was expecting $a and $b to keep their references like $c does. It's almost like they are being passed by value since they revert to their original value even though they are passed by reference.
Is this correct behavior?
https://3v4l.org/uHaGq
Thanks for your help.
The following code:
<?php
$a = null;
$b = 'test';
$c = null;
$test1 = function() use (&$a, &$b, &$c)
{
$value = 1;
$a = &$value;
$b = &$value;
$c = array(
'c' => &$value,
);
};
$test1();
echo 'a: ';
var_dump($a);
echo 'b: ';
var_dump($b);
echo 'c: ';
var_dump($c);
exit;
Resulted in this output:
a: NULL
b: string(4) "test"
c: array(1) {
["c"]=>
int(1)
}
But I expected this output instead:
a: int(1)
b: int(1)
c: array(1) {
["c"]=>
int(1)
}
PHP Version
PHP 7.4.26
Operating System
No response
Before $a = &$value is evaluated, the local $a and the global $a reference the same value (null). After that reference assignment, the local $a and the local $value reference the same value (1). As such, the local $a looses the reference to the value null. That does not happen with $c, because you're not assigning by-ref.