PHP static局部静态变量和全局静态变量总结_PHP

WBOY
Release: 2016-06-01 11:56:23
Original
906 people have browsed it

静态局部变量的特点:

1.不会随着函数的调用和退出而发生变化,不过,尽管该变量还继续存在,但不能使用它。倘若再次调用定义它的函数时,它又可继续使用,而且保存了前次被调用后留下的值
2.静态局部变量只会初始化一次
3.静态属性只能被初始化为一个字符值或一个常量,不能使用表达式。即使局部静态变量定义时没有赋初值,系统会自动赋初值0(对数值型变量)或空字符(对字符变量);静态变量的初始值为0。
4.当多次调用一个函数且要求在调用之间保留某些变量的值时,可考虑采用静态局部变量。虽然用全局变量也可以达到上述目的,但全局变量有时会造成意外的副作用,因此仍以采用局部静态变量为宜。
复制代码 代码如下:
function test()
{
    static $var = 5;  //static $var = 1+1;就会报错
    $var++;
    echo $var . ' ';
}

 
test(); //2
test(); //3
test(); //4
echo $var; //报错:Notice: Undefined variable: var

关于静态全局变量:
复制代码 代码如下:
//全局变量本身就是静态存储方式,所有的全局变量都是静态变量
function static_global(){
    global $glo;
    $glo++;
    echo $glo.'
';
}

static_global(); //1
static_global(); //2
static_global(); //3
echo $glo . '
'; //3

所以静态全局变量使用并不多。

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!