php 函数引用调用问题

WBOY
Release: 2016-06-23 13:47:35
Original
992 people have browsed it

function &test(){  
    static $b = 1;  
    $b += 2;  
    return $b;  
}  
$a = &test();  
$a =8;  
$c = &test();  // 这里再次调用test() 函数,为什么不再执行static $b = 1;这个语句。因为结果表明此时$c=10.
// 如果将static去掉,结果是3. 这个怎么解释?谢谢!
echo $c;


回复讨论(解决方案)

static修饰了变量$b,那么它就是一直存在的,去掉static,那么每次调用都会初始化一次
因为$a = &test();(加了&,地址传递)所以$a被改变,那么静态变量$b的值也被改变,所以在执行$c = &test();时,此时$b的值是8,返回10

static修饰了变量$b,那么它就是一直存在的,去掉static,那么每次调用都会初始化一次
因为$a = &test();(加了&,地址传递)所以$a被改变,那么静态变量$b的值也被改变,所以在执行$c = &test();时,此时$b的值是8,返回10


把语句改成
function &test() {
static $b = 1;
static $b = 100;
static $b = 1000;
        // $b = 1000;
$b += 2;
return $b;
} 又测试了下,原来静态存在的不能再用静态方式去修改它。但是又不报错,有点受不了,呵呵~。

静态变量只在声明时赋初值,静态变量具有全局变量的性质,只是作用域不同

静态变量只存在于函数作用域内,也就是说,静态变量只存活在栈中。一般的函数内变量在函数结束后会释放,比如局部变量,但是静态变量却不会。就是说,下次再调用这个函数的时候,该变量的值会保留下来。

静态变量只在声明时赋初值,静态变量具有全局变量的性质,只是作用域不同 +1

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!