<?php
function foo(&$var)
{
$var =& $GLOBALS["baz"];
}
foo($bar);
?>
As the example bellow, which just say out the reference is equal to the pointer of variables as c.
See the $var as the pointer, firstly it point to the $bar, then as we use "=&" assign it, it change the pointer itself(not content) and point to the $GLOBALS["baz"].In this flow, the $bar change neighter its ponter nor the content.
This is just the concept in C, isn't it?
A little warning: my function my_make_vars() (see other post) has a side-effect, of course...
$a=array('x'=>1,'y'=>2);
$x0=&$a['x'];
my_make_vars($a);
# $x0 now is not any more a reference to $a['x'] !!!
$x1=&$a['x']; # (but $x1 is, because done after the my_make_vars($a);)
$x=4; print $a['x'].' '; # ->4
print $x0.' '.$x1; # -> 1 4
The manual states: "There's no way to bind $bar in the calling scope to something else using the reference mechanism"
This is actually incorrect. It is possible to bind $bar to another object. The given example doesn't work for obvious reasons: $var is redeclared as an alias for $GLOBALS["baz"], instead of an alias for $bar.
You should use an ordinary assignment to assign another object to the same variable. This works because variables containing objects actually contain a reference to that object, and the reference is copied to $var, and therefore is copied to $bar as well.
When using primitive values, such as integers or strings, the values itself are copied. In the example (when excluding the ampersand from the assignment), suppose that $GLOBALS['baz'] contains the value 3, after calling foo($bar), $bar will contain the integer 3, but they won't point to the same memory space.
The correct sentence would be thus:
"There's no way make $bar in the calling scope an alias for something else using the reference mechanism"
You can think of references as pointers, if you translate a=b into "*a = *b" and a =& b into "a=b".
Let's translate to C:
<?PHP
const int c_1 = 1, c_2 = 2;
int * a = &c_1;
int * b = &c_2;
void foo (int * var)
{
var = a;
}
?>
Here, it's obvious that calling foo(b) won't change the value of a, because var is a copy of b. You also have to be careful: order does matter. I could draw a diagram, but I won't.
4/8 首页 上一页 2 3 4 5 6 7 下一页 尾页 |