;
$bar = 'bar';
function foo (&$var)
{
$var =& $GLOBALS["baz"];
}
echo '$GLOBALS[baz]: ' . $GLOBALS["baz"] . "<BR>n"; echo "$bar: $bar <BR>n"; foo($bar);
echo "$bar: $bar <BR>n"; $bar = 'bar';
echo '$GLOBALS[baz]: ' . $GLOBALS["baz"] . "<BR>n"; ?>
If you change the calling of foo($bar) with $bar =& $GLOBALS["baz"]; it all works as expected.
So the assertion, "references are not like pointers," might be a bit confusing but it is fair.
The assertion, "references are not like pointers," is a bit confusing.
In the example, the author shows how assigning a reference to a formal parameter that is also a reference does not affect the value of the actual parameter. This is exactly how pointers behave in C. The only difference is that, in PHP, you don't have to dereference the pointer to get at the value.
-+-+-
int bar = 99;
void foo(int* a)
{
a = &bar;
}
int main()
{
int baz = 1;
foo(&baz);
printf("%dn", baz);
return 0;
}
-+-+-
The output will be 1, because foo does not assign a value to the dereferenced formal parameter. Instead, it reassigns the formal parameter within foo's scope.
Alternatively,
-+-+-
int bar = 99;
void foo(int* a)
{
*a = bar;
}
int main()
{
int baz = 1;
foo(&baz);
printf("%dn", baz);
return 0;
}
-+-+-
The output will be 9, because foo dereferenced the formal parameter before assignment.
So, while there are differences in syntax, PHP references really are very much like pointers in C.
I would agree that PHP references are very different from Java references, as Java does not have any mechanism to assign a value to a reference in such a way that it modifies the actual parameter's value.
|