免费邮箱 |加入收藏 | 会员中心 | 我要投稿 | RSS
您当前的位置:首页 > PHP专区 > PHP技巧

引用的解释

时间:2011-05-16 15:55:22  来源:站内  作者:潘春会

//$tmp has the desired reference
}

marco at greenlightsolutions dot nl (16-Nov-2007 06:38)

 

 

 

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; // should be a deep cloning
$c[1]="C";
var_dump($a[1]); // yields 'C' instead of 'A'
?>

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.

warnickr at gmail dot com (10-Nov-2007 05:15)

 

 

 

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);
来顶一下
返回首页
返回首页
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表
推荐资讯
如何找出DHCP地址池里未使用的IP地址
如何找出DHCP地址池里
国内常用的DNS列表
国内常用的DNS列表
Linux邮件服务器软件比较
Linux邮件服务器软件比
学用纯CSS打造可折叠树状菜单
学用纯CSS打造可折叠树
相关文章
栏目更新
栏目热门