Home >Backend Development >PHP Tutorial >PHP variable reference (&), function reference and object reference_PHP tutorial
1. Variable reference
PHP reference pointers of two variables point to the same memory address
$a="ABC"; $b =&$a; echo $a;//这里输出:ABC echo $b;//这里输出:ABC $b="EFG"; echo $a;//这里$a的值变为EFG 所以输出EFG echo $b;//这里输出EFG
2. Function reference transfer (call by address)
function test(&$a) { $a=$a+100; } $b=1; echo $b;//输出1 test($b); //这里$b传递给函数的其实是$b的变量内容所处的内存地址,通过在函数里改变$a的值 就可以改变$b的值了 echo "<br>"; echo $b;//输出101 ?>
3. Function reference return
function &test() { static $b=0;//申明一个静态变量 $b=$b+1; echo $b; return $b; } $a=test();//这条语句会输出 $b的值 为1 $a=5; $a=test();//这条语句会输出 $b的值 为2 $a=&test();//这条语句会输出 $b的值 为3 $a=5; $a=test();//这条语句会输出 $b的值 为6
Explanation below:
In this way, $a=test(); actually does not get a reference return from the function. It is no different from an ordinary function call. As for the reason: This is a rule of PHP
When calling a function through $a=&test(), its function is to point the memory address of the $b variable in return $b and the memory address of the $a variable to the same place
That is to say, the effect equivalent to this is produced ($a=&$b;), so changing the value of $a also changes the value of $b, so after executing
4. Object reference (PHP5)
class foo { public $bar = 1; } $a = new foo; //$a其实也是一个引用 $b = $a; //拷贝引用 ($a)=($b)={id1} $a->bar = 2; echo "b->bar = $b->bar\n"; $b->bar = 3; echo "a->bar = $a->bar\n"; //修改了b,但实际上是修改了a和b所引用的同一个对象 //并不会引发 Copy On Write 创建一个新对象b $a = new foo; //$a被修改为一个新的引用,$b没有改变 //($a)={id2} ($b)={id1} $a->bar = 4; echo "b->bar = $b->bar\n"; $b = &$a; //显式地使用引用,b成为“对象的引用”的引用 $a = new foo; //($a)={id3} ($b)=&($a)=&{id3} $a->bar = 5; echo "b->bar = $b->bar\n" //==output==== b->bar = 2 a->bar = 3 b->bar = 3 b->bar = 5