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

引用的解释

时间:2011-05-16 15:55:22  来源:站内  作者:潘春会
1];   // Unused reference
   
$array2 = $array1// reference now also applies to $array2 !
   
$array2[1]=22;      // (changing [0] will not affect $array1)
   
print_r($array1);
?>
Produces:
    Array
    (
    [0] => 1
    [1] => 22    // var_dump() will show the & here
    )

I fixed my bug by rewriting the code without references, but it can also be fixed with the unset() function:
<?php
    $array1
= array(1,2);
   
$x = &$array1[1];
   
$array2 = $array1;
    unset(
$x); // Array copy is now unaffected by above reference
   
$array2[1]=22;
   
print_r($array1);
?>
Produces:
    Array
    (
    [0] => 1
    [1] => 2
    )

Radek at cz (26-Apr-2008 02:35)

 

 

 

It took me a long while until I fully understood the sentence mentioned above:

"They (references) are not like C pointers; instead, they are symbol table aliases."

Here is a little example to that.

<?php
class AnyClass {
    public
$member;
    public function
__construct($val) {
       
$this->member = $val;
    }
}

$manyObjects = array();
$obj = null;

for(
$i = 0; $i < 5;$i++) {
   
$obj = new AnyClass($i); // create new instance
   
$manyObjects[] = &$obj;
来顶一下
返回首页
返回首页
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表
推荐资讯
如何找出DHCP地址池里未使用的IP地址
如何找出DHCP地址池里
国内常用的DNS列表
国内常用的DNS列表
Linux邮件服务器软件比较
Linux邮件服务器软件比
学用纯CSS打造可折叠树状菜单
学用纯CSS打造可折叠树
相关文章
栏目更新
栏目热门