reference引用

来源:互联网 发布:愿你知我心 无损 编辑:程序博客网 时间:2024/05/10 07:08

/***************by Jiangong SUN***************/

 

<?php
//$a =& $b;
//$a和$b完全相等,指向了同一个内存地址。如果a改变了值,b也将改变值。
//Note: $a and $b are completely equal here. $a is not pointing to $b or vice versa. $a and $b are pointing to the same place.
//Note: If arrays with references are copied, their values are not dereferenced. This is valid also for arrays passed by value to functions.
//Note: If you assign, pass, or return an undefined variable by reference, it will get created.

//toto tata指向同一个内存地址,改变toto或tata的值,另一个变量的值也随之改变
$toto = 'hello';
$tata =& $toto;
$tata = 'new world';
echo $tata; // new world
echo "<br>";
echo $toto;  // new world
echo "<br>";

//One important thing to note is that only named variables may be assigned by reference.
$foo = 25;
$bar = &$foo;      // This is a valid assignment.
//$bar =&(24 * 7);  // Invalid; references an unnamed expression.
function test()
{
   return 25;
}
//$bar = &test();    // Invalid.

function test1(&$a)
{
$a=$a+100;
}
$b=1;
echo $b;//输出1
test1($b);  //这里$b传递给函数的其实是$b的变量内容所处的内存地址,通过在函数里改变$a的值 就可以改变$b的值了
echo "<br>";
echo $b;//输出101
echo "<br>";

 

//unset When you unset the reference, you just break the binding between variable name and variable content.
//This does not mean that variable content will be destroyed.
$a = 1;
$b =& $a;
unset($a);
echo "<br />";
echo $a; //输出 undefined variable
echo $b;  //输出1

?>

原创粉丝点击