日期:2013-05-25  浏览次数:20501 次

在php4年代, 对象的引用是通过一个简单的 "&" 符号来实现的.
在php5中($obj1 = $obj2;)默认就是引用的方式, 不需要刻意的加一个 "&" 符号,但是在php5中仍然还保留了php4种

的这用引用方式.

但是这两种方式到底有什么区别呢,下面让我们来看看分析一下.

老的引用方式实现方式如下(下面的一段代码可以在php4和php5上跑):
代码1:
    class test{ function get(){return "aaaaa";} }
    $t1 = new test();
    $t2 = &$t1;
    echo $t1->get()."
";
    echo $t2->get()."
";
?>

这样变量 $t1 和 $t2 就指向了同一个对象, 他们共享内存中的同一个对象.

代码2:
    class test{ function get(){return "aaaaa";} }
    $t1 = new test();
    $t2 = &$t1;
    unset($t1);
    echo ($t1===null)? "t1 is null.
": "t1 is not null.
";
    echo $t2->get()."
";
?>

t1变量被unset后,t1变成了null, 但是t2仍然还是指向原来的对象.

代码3:
    class test{ function get(){return "aaaaa";} }
    $t1 = new test();
    $t2 = &$t1;
    $t1 = null;
    echo ($t1===null)? "t1 is null.
": "t1 is not null.
";
    echo ($t1===null)? "t2 is null.
": "t2 is not null.
";
?>

t1=null后,t1变成了null, 可是t2竟然也变成了null

天啊,t1和t2的结果怎么会不一样呢? 折腾了半天才想明白, 通过"&" 引用的方式,实际上不应该叫做"引用",应该叫做"传址", 传址的概念在c语言里面是很明确的, 并且代码的书写方式是很类似的. 最开始,还以为这个和java里面对象引用的处理方式一样呢, 笨.....................啊!.

下面再来看看 php5 中的引用的方式吧.
代码4:
class test1{
    public function aa(){
        echo "aaaaaaaaaaa
";
    }
    public function __destruct(){
        echo "game over!";
    }
}
$t1 = new test1();
$t2 = $t1;
$t1 = null;
echo $t2->aa();
unset($t2);
?>

代码5:
class test1{
    public function aa(){
        echo "aaaaaaaaaaa
";
    }
    public function __destruct(){
        echo "game over!";
    }
}
$t1 = new test1();
$t2 = $t1;
unset($t1);
echo $t2->aa();
unset($t2);
?>

发现没有,代码4和代码5 的运行结果完全相同, 这个结果到是令人满意, 和java的对象引用的实现方式终于一致了.

--------------------------------------------------
结论, 结果证明php4的"&"这种方式是"传址", 而php5的默认的方式是"引用"(唠叨批).
 
在 php5 中引用对象的时候要根据实际的情况选择适当的引用的方式. 如果程序比较大,引用同一个对象的变量比较多,并且希望用完该对象后手工清除它,个人建议用 "&" 方式,然后用$var=null的方式清除. 其它时候还是用php5的默认方式吧. 另外, php5中对于大数组的传递,建议用 "&" 方式, 毕竟节省内存空间使用吗.