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

引用不是什么

时间:2011-05-16 15:57:52  来源:站内  作者:潘春会
;
$bar = 'bar';

function
foo (&$var)
{
   
$var =& $GLOBALS["baz"];
}

// Before 'binding' $bar to $GLOBALS["baz"] using a function
echo '$GLOBALS[baz]: ' . $GLOBALS["baz"] . "<BR>n";    // Output is 'globals_baz'
echo "$bar: $bar <BR>n";    // Output is 'bar'

foo($bar);

// After (what you may expected to be a) binding you should see that $bar is the same as $GLOBALS[baz]:
echo "$bar: $bar <BR>n"; // it didn't work: output is still 'bar' (not 'globals_baz')

// And setting $bar should set $GLOBALS[baz]:
$bar = 'bar';
echo
'$GLOBALS[baz]: ' . $GLOBALS["baz"] . "<BR>n"; // it didn't work, too: output is still 'globals_baz' (not 'bar')
?>

If you change the calling of foo($bar) with $bar =& $GLOBALS["baz"]; it all works as expected.
So the assertion, "references are not like pointers," might be a bit confusing but it is fair.

ansonyumo at email dot com (28-Feb-2004 05:47)

 

 

 

The assertion,  "references are not like pointers," is a bit confusing.

In the example, the author shows how assigning a reference to a formal parameter that is also a reference does not affect the value of the actual parameter. This is exactly how pointers behave in C. The only difference is that, in PHP, you don't have to dereference the pointer to get at the value.

-+-+-
int bar = 99;

void foo(int* a)
{
    a = &bar;
}

int main()
{
   int baz = 1;
   foo(&baz);
   printf("%dn", baz);
   return 0;
}
-+-+-

The output will be 1, because foo does not assign a value to the dereferenced formal parameter. Instead, it reassigns the formal parameter within foo's scope.

Alternatively,
-+-+-
int bar = 99;

void foo(int* a)
{
    *a = bar;
}

int main()
{
   int baz = 1;
   foo(&baz);
   printf("%dn", baz);
   return 0;
}
-+-+-

The output will be 9, because foo dereferenced the formal parameter before assignment.

So, while there are differences in syntax, PHP references really are very much like pointers in C.

I would agree that PHP references are very different from Java references, as Java does not have any mechanism to assign a value to a reference in such a way that it modifies the actual parameter's value.

schultz __at__ widescreen __dot__ ch

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