在 PHP 中引用意味着用不同的名字访问同一个变量内容。这并不像 C 的指针,替代的是引用是符号表别名。注意在 PHP 中,变量名和变量内容是不一样的,因此同样的内容可以有不同的名字。
1、引用传递
function foo ( &$var )
{$var++;}
foo ($a); // 注意在函数调用时没有引用符号 - 只有函数定义中有。光是函数定义就足够使参数通过引用来正确传递了
2、引用返回
function &init_users()
{ ... return $cls;}
使用引用返回,函数里面必须用return返回值;如果有类,类实例后,”拷贝“实例的引用返回函数时,别忘了加&符号。如:$obj =new A(),$newobj = &A->init_users();,这里,如果不加&,就纯属拷贝了,当后面fun_ref()函数的值改变时,$newobj也不会跟着变!
$user = & init_users();
function &init_users()
{ ... return $cls;}
3、取消引用
当 unset 一个引用,只是断开了变量名和变量内容之间的绑定。这并不意味着变量内容被销毁了。
$a = "hihaha";
$b = &$a;
unset($b);
echo $a; // shows "hihaha"---------------------------------
下面这些例子说明了引用传递、取消引用及删除变量的作用:
这里有个php引用的例子,好好看一遍:
//if you do:
$a = "hihaha";
$b = &$a;
$c = "eita";
$b = $c;
echo $a; // shows "eita"
$a = "hihaha";
$b = &$a;
$c = "eita";
$b = &$c;
echo $a; // shows "hihaha"
$a = "hihaha";
$b = &$a;
$b = null;
echo $a; // shows nothing (both are set to null)
$a = "hihaha";
$b = &$a;
unset($b);
echo $a; // shows "hihaha"
$a = "hihaha";
$b = &$a;
$c = "eita";
$a = $c;
echo $b; // shows "eita"
$a = "hihaha";
$b = &$a;
$c = "eita";
$a = &$c;
echo $b; // shows "hihaha"
$a = "hihaha";
$b = &$a;
$a = null;
echo $b; // shows nothing (both are set to null)
$a = "hihaha";
$b = &$a;
unset($a);
echo $b; // shows "hihaha"
?>