//$tmp has the desired reference
}
I ran into a bit of a problem recently, with an array copy resulting in a reference copy of one of the elements instead of a clone. Sample code:
<?php
$a=array(1 => "A");
$b=&$a[1];
$c=$a; $c[1]="C";
var_dump($a[1]); ?>
After some searching, I found that it was a known bug which would be too costly to fix (see http://bugs.php.net/bug.php?id=20993). There was supposed to be some documentation on this behaviour on this page:
"Due to peculiarities of the internal workings of PHP, if a reference is made to a single element of an array and then the array is copied, whether by assignment or when passed by value in a function call, the reference is copied as part of the array. This means that changes to any such elements in either array will be duplicated in the other array (and in the other references), even if the arrays have different scopes (e.g. one is an argument inside a function and the other is global)! Elements that did not have references at the time of the copy, as well as references assigned to those other elements after the copy of the array, will behave normally (i.e. independent of the other array)."
However, this paragraph appears to have been removed from this page at some point, presumably because it was a bit obscure. The comments section seem to be a proper place for this, though.
I must say that it has been rather confusing following all of the explanations of PHP references, especially since I've worked a lot with C pointers. As far as I can tell PHP references are the same as C pointers for all practical purposes. I think a lot of the confusion comes from examples like the one shown below where people expect that a C pointer version of this would change what $bar references.
<?php
function foo(&$var)
{
$var =& $GLOBALS["baz"];
}
foo($bar);
?>
This is not the case. In fact, a C pointer version of this example (shown below) would behave exactly the same way (it would not modify what bar references) as the PHP reference version.
int baz = 5;
int* bar;
void foo(int* var)
{
var = &baz;
}
foo(bar);
In this case, just as in the case of PHP references, the call foo(bar) doesn't change what bar references. If you wanted to change what bar references, then you would need to work with a double pointer like so:
int baz = 5;
int* bar;
void foo(int** var)
{
*var = &baz;
}
foo(&bar);
12/24 首页 上一页 10 11 12 13 14 15 下一页 尾页 |