Thursday 18 December 2008 17:16 Every now and then, when you least expect it, PHP behaves in an unexpected way. I was ready to file a bugreport, when I noticed it was documented behaviour.
By Casper Langemeijer Take a look at the following code:
function b()
{
global $a;
$b = 'bar';
$a = &$b;
}
$a = 'foo';
b();
echo $a;
What do you think is the value of $a after calling b()? The correct answer is 'foo'. If we remove the ampersand in '$a = &$b;' the value will be: 'bar'.
This behaviour can be explained as following:
In function b() the 'global $a' statement creates new a local variable $a as a reference to the global $a variable. '$a = &$b' then changes the local $a variable as a reference to $b. The global $a variable is not touched.
To achieve a sane result use the following construction, create the reference first, then assign a new value:
function b()
{
global $a;
$b = &$a
$b = 'bar';
}
I still think this should be considered flawed implementation, if not simply broken.