php 函数引用调用问题

WBOY
Libérer: 2016-06-23 13:47:35
original
993 Les gens l'ont consulté

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

Étiquettes associées:
source:php.cn
Déclaration de ce site Web
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn
Tutoriels populaires
Plus>
Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal
À propos de nous Clause de non-responsabilité Sitemap
Site Web PHP chinois:Formation PHP en ligne sur le bien-être public,Aidez les apprenants PHP à grandir rapidement!