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

引用不是什么

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

Anonymous (12-May-2008 12:52)

 

 

 

<?php
function foo(&$var)
{
   
$var =& $GLOBALS["baz"];
}
foo($bar);
?>

As the example bellow, which just say out the reference is  equal to the pointer of variables as c.
See the $var as the pointer, firstly it point to the $bar, then as we use "=&" assign it, it change the pointer itself(not content) and point to the $GLOBALS["baz"].In this flow, the $bar change neighter its ponter nor the content.
This is just the concept in C, isn't it?

frank (21-Jan-2008 06:46)

 

 

 

A little warning: my function my_make_vars()  (see other post) has a side-effect, of course...

$a=array('x'=>1,'y'=>2);

$x0=&$a['x'];

my_make_vars($a);

# $x0  now is not any more a reference to  $a['x'] !!!

$x1=&$a['x'];  # (but $x1 is, because done after the my_make_vars($a);)
$x=4; print $a['x'].' '; #  ->4
print $x0.' '.$x1;   # -> 1 4

Stevel (04-Feb-2007 12:30)

 

 

 

The manual states: "There's no way to bind $bar in the calling scope to something else using the reference mechanism"

This is actually incorrect. It is possible to bind $bar to another object. The given example doesn't work for obvious reasons: $var is redeclared as an alias for $GLOBALS["baz"], instead of an alias for $bar.

You should use an ordinary assignment to assign another object to the same variable. This works because variables containing objects actually contain a reference to that object, and the reference is copied to $var, and therefore is copied to $bar as well.

When using primitive values, such as integers or strings, the values itself are copied. In the example (when excluding the ampersand from the assignment), suppose that $GLOBALS['baz'] contains the value 3, after calling foo($bar), $bar will contain the integer 3, but they won't point to the same memory space.

The correct sentence would be thus:
"There's no way make $bar in the calling scope an alias for something else using the reference mechanism"

Tee Cee (20-Aug-2006 08:59)

 

 

 

You can think of references as pointers, if you translate a=b into "*a = *b" and a =& b into "a=b".

Let's translate to C:

<?PHP
const int c_1 = 1, c_2 = 2;
int * a = &c_1;
int * b = &c_2;

void foo (int * var)
{
   var =
a;
}
?>

Here, it's obvious that calling foo(b) won't change the value of a, because var is a copy of b. You also have to be careful: order does matter. I could draw a diagram, but I won't.
来顶一下
返回首页
返回首页
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表
推荐资讯
如何找出DHCP地址池里未使用的IP地址
如何找出DHCP地址池里
国内常用的DNS列表
国内常用的DNS列表
Linux邮件服务器软件比较
Linux邮件服务器软件比
学用纯CSS打造可折叠树状菜单
学用纯CSS打造可折叠树
相关文章
栏目更新
栏目热门