Jump to content
  • Hello visitors, welcome to the Hacker World Forum!

    Red Team 1949  (formerly CHT Attack and Defense Team) In this rapidly changing Internet era, we maintain our original intention and create the best community to jointly exchange network technologies. You can obtain hacker attack and defense skills and knowledge in the forum, or you can join our Telegram communication group to discuss and communicate in real time. All kinds of advertisements are prohibited in the forum. Please register as a registered user to check our usage and privacy policy. Thank you for your cooperation.

    TheHackerWorld Official

PHP 静态局部变量和静态全局变量

 Share


Recommended Posts

PHP static静态局部变量和静态全局变量总结_胡德咏的博客-CSDN博客  https://blog.csdn.net/u010620626/article/details/43965879

使用静态局部变量的原因是它不能被外部使用,但是它的值依然在每次使用后保留。虽然使用全局变量可以实现相同的功能,但是它经常会造成意外。
静态局部变量的特点:

    1.不会随着函数的调用和退出而发生变化,不过,尽管该变量还继续存在,但不能使用它。倘若再次调用定义它的函数时,它又可继续使用,而且保存了前次被调用后留下的值

    2.静态局部变量只会初始化一次

    3.静态属性只能被初始化为一个字符值或一个常量,不能使用表达式。即使局部静态变量定义时没有赋初值,系统会自动赋初值0(对数值型变量)或空字符(对字符变量);静态变量的初始值为0。

    4.当多次调用一个函数且要求在调用之间保留某些变量的值时,可考虑采用静态局部变量。虽然用全局变量也可以达到上述目的,但全局变量有时会造成意外的副作用,因此仍以采用局部静态变量为宜。

//@link  http://www.phpddt.com
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.'<br>';
}
 
static_global(); //1
static_global(); //2
static_global(); //3
echo $glo . '<br>'; //3

 

静态变量:

function static_global(){
    global $glo;
    $glo++;
    echo $glo.'<br>';
}

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

 

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

Link to post
Link to comment
Share on other sites

 Share

discussion group

discussion group

    You don't have permission to chat.
    • Recently Browsing   0 members

      • No registered users viewing this page.
    ×
    ×
    • Create New...