?>
In the same sense of an array, $var and $var2 are like keys to the same value. The value being the string in memory.
When you call a function that uses a reference, the reference is not less than the variable given as the argument, or anything more than it.
It is that same variable except with a different name.
Here's a thought to settle the whole (are/aren't) debacle...
References are *like* pointers, but are not *identical to* pointers. The best comparison I could give is that references are "scope-limited pointers". You can change the value of one variable by changing the other as long as it is in the same scope. Once you set outside that scope (i.e. calling a function), references cease to act the same as pointers.
Example 1:
$a = 'eh';
$b = & $a;// $b == 'eh'
$c = & $b;// $c == 'eh'
$a = 'meh';// $c == 'meh'
... changing a's value will change c's value. This is where references are like pointers in C/C++
Example 2:
$GLOBALS["b"] = 'b_val';
$c = 'c_val';
function foo (&$var)
{
$var =& $GLOBALS["b"]; //affects only 'var' copy
}
$GLOBALS["b"] = & $a; // $GLOBALS["b"] == 'a_val'
foo($c); // the value of c will remain 'c_val'
... It might help to think of it in a different way. A calling the function by reference mimics the following behavior:
$var = & $c;
... so when you if you execute this line in foo():
$var =& $GLOBALS["b"];
, you are just re-referencing var from what it was "referenced to" at the function call to a new reference.
This is where references are *not* like pointers in C/C++ as the value of c is not changed as it would be if a similiar function that implemented pointers were used.
I hope this clears up the confusion.
Note references in array elements behave very much the same as pointers. The following seems to defy the simple definition of array assignment as copy-by-value:
unset($a);
unset($b);
$a[1]=1;
$a[2]=&$a[1];
$b=$a;
$b[2]=7;
print_r($a);
Array
(
[1] => 7
[2] => 7
)
print_r($b);
Array
(
[1] => 7
[2] => 7
)
- so array assignment is a very shallow copy-by-value, which preserves reference associations in any array elements. Oddly, I believe PHP lacks a deep array-copy-by-value function.
References are not like pointers.
If you try the example above in C/C++ you will find that after calling foo(var) you can get or set the value of $GLOBALS["baz"] by reading or writing variable 'var' (I didn't actually try it, but I vaguely remember it works this way).
In PHP this is also true if you do:
<?PHP
$var =& $GLOBALS["baz"];
?>
but *IT IS NOT* if you use a function to do that, in spite of
- using a reference as a parameter (function foo(&$var)) and
- assigning it a reference to the variable you want to bind ($var =& $GLOBALS["baz"]) inside the function
I tried this:
<?PHP
$GLOBALS["baz"] = 'globals_baz'
6/8 首页 上一页 4 5 6 7 8 下一页 尾页 |