PHP: making a copy of a reference variable
If I make a copy of a reference variable. Is the new variable a pointer or does it hold the value of the variable the pointer w开发者_开发百科as referring to?
It holds the value. If you wanted to point, use the &
operator to copy another reference:
$a = 'test';
$b = &$a;
$c = &$b;
Let's make a quick test:
<?php
$base = 'hello';
$ref =& $base;
$copy = $ref;
$copy = 'world';
echo $base;
Output is hello
, therefore $copy
isn't a reference to %base
.
Let me murk the water with this example:
$a = array (1,2,3,4);
foreach ($a as &$v) {
}
print_r($a);
foreach ($a as $v) {
echo $v.PHP_EOL;
}
print_r($a);
Output:
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
)
1
2
3
3
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 3
)
精彩评论