PHP 中的引用(reference)

来源:互联网 发布:社交网络好友推荐算法 编辑:程序博客网 时间:2024/04/29 21:57

     从c/c++角度学习php时,最令人模糊的概念便是php中的引用。php中引用的最大特点便是可以在任何时候改变引用的对象。如果到此就结束的话,那么也没什么大不了的。关键是php中的static和global定义的变量是以引用来实现的,按php中的原话是 implements the static and global modifier for variables in terms of references!!在加上php引用的最大特点就会产生一些看起来奇怪的事情。

 

static 变量

<?php

    function test_static_ref(){

        static $obj;

       

        var_dump($obj);

 

        if(!isset($obj)){

              $obj=&new stdclass;//离开作用域后,静态变量不会记住引用值

        }

    }

 

    test_static_ref();//print NULL

    test_static_ref();//print NULL

?>

 

global变量

<?php

$obj="abc";
function test_global_ref
() {
    global 
$obj
;//reference to global $obj="abc"
    
$obj = &new stdclass
;//change reference object to stdclass, so $obj="abc" remain same.
}

var_dump($obj);//print abc

?>