原文:https://www.cnblogs.com/52php/p/5658317.html
函数的引用返回
先看代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
<?php 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 ?> |
下面解释下:
通过这种方式$a=test();得到的其实不是函数的引用返回,这跟普通的函数调用没有区别,至于原因:这是PHP的规定,PHP规定通过$a=&test(); 方式得到的才是函数的引用返回,至于什么是引用返回呢(PHP手册上说:引用返回用在当想用函数找到引用应该被绑定在哪一个变量上面时。) 这句狗屁话,害我半天没看懂。
用上面的例子来解释就是
$a=test() 方式调用函数,只是将函数的值赋给$a而已,而$a做任何改变,都不会影响到函数中的$b,而通过 $a=&test() 方式调用函数呢, 他的作用是将 return $b 中的$b变量的内存地址与$a变量的内存地址,指向了同一个地方,即产生了相当于这样的效果 “$a=&$b;” 所以改变$a的值 也同时改变了$b的值,所以在执行了
1
2
|
$a =&test(); $a =5; |
以后,$b的值变为了5。
这里是为了让大家理解函数的引用返回才使用静态变量的,其实函数的引用返回多用在对象中
另附一个PHP官方例子:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
|
//This
is the way how we use pointer to access variable inside the class. <?php class talker{ private $data = 'Hi' ; public function &
get(){ return $this ->data; } public function out(){ echo $this ->data; } } $aa = new talker(); $d =
& $aa ->get(); $aa ->out(); $d = 'How' ; $aa ->out(); $d = 'Are' ; $aa ->out(); $d = 'You' ; $aa ->out(); ?> //the
output is "HiHowAreYou" |