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

引用不是什么

时间:2011-05-16 15:57:52  来源:站内  作者:潘春会
(26-Jan-2004 11:57)

 

 

 

A not so simple Workaround...but still doable...have fun

class My{
    var $value;
   
    function get1(&$ref){
        $ref[] =& $this;
    }
   
    function get2(&$ref){
        $ref =& $this;
    }
   
    function get3(&$ref){
        $ref = $this;
    }
}

$m = new My();

$m->value = 'foo';
$m->get1($ref=array());
$m1 =& $ref[0];
$m1->value = 'bar';
echo "n".'Works but is ugly...';
echo "n".' m:'. get_class($m) . '->value = '. $m->value;
echo "n".' m1:'. get_class($m1) . '->value = '. $m1->value;

echo "n".'Does not work because references are not pointers...';
$m->value = 'foo';
$m->get2($m2);
$m2->value = 'bar';
echo "n".' m:'. get_class($m) . '->value = '. $m->value;
echo "n".' m2:'. get_class($m2) . '->value = '. $m2->value;

$m->value = 'foo';
$m->get3($m3);
$m3->value = 'bar';
echo "n".'Does not work becuase it is set to a copy';
echo "n".' m:'. get_class($m) . '->value = '.$m->value;
echo "n".' m3:'. get_class($m3) . '->value = '. $m3->value;

christian at kno dot at (13-Oct-2001 09:04)

 

 

 

As said above references are not pointers.

Following example shows a difference between pointers and references.

This Code
<?
    $b = 1;
    $a =& $b;

    print("<pre>");
    print("$a === $b: ".(($a === $b) ? "ok" : "failed")."n");
    print("unsetting $a...n");
    unset($a);
    print("now $a is ".(isset($a) ? "set" : "unset")." and $b is ".(isset($b) ? "set" : "unset")."n");
    print("</pre>");

    $b = 1;
    $a =& $b;

    print("<pre>");
    print("$a === $b: ".(($a === $b) ? "ok" : "failed")."n");
    print("unsetting $b...n");
    unset($b);
    print("now $a is ".(isset($a) ? "set" : "unset")." and $b is ".(isset($b) ? "set" : "unset")."n");
    print("</pre>");
?>

will produce this output:
---------
$a === $b: ok
unsetting $a...
now $a is unset and $b is set

$a === $b: ok
unsetting $b...
now $a is set and $b is unset
---------

So you see that $a and $b are identical ($a === $b -> true), but if one of both is unset, the other is not effected.
来顶一下
返回首页
返回首页
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表
推荐资讯
如何找出DHCP地址池里未使用的IP地址
如何找出DHCP地址池里
国内常用的DNS列表
国内常用的DNS列表
Linux邮件服务器软件比较
Linux邮件服务器软件比
学用纯CSS打造可折叠树状菜单
学用纯CSS打造可折叠树
相关文章
栏目更新
栏目热门