zoukankan      html  css  js  c++  java
  • 值不丢失,虽然仅在局部函数中存在

    w

    http://php.net/manual/en/language.variables.scope.php

    http://php.net/manual/zh/language.variables.scope.php 

    <?php
    function test()
    {
        $a = 0;
        echo $a;
        $a++;
    }
    
    test();
    test();
    test();
    test();
    <?php
    function test()
    {
        static $a = 0;
        echo $a;
        $a++;
    }
    
    test();
    test();
    test();
    test(); 

    //0000

    //0123

    <?php
    function test()
    {
        static $a = 0;
        echo $a;
        $a++;
    }
    
    test();
    test();
    test();
    test();
    echo $a;

    //0123 Notice: Undefined variable: a

    变量范围的另一个重要特性是静态变量(static variable)。静态变量仅在局部函数域中存在,但当程序执行离开此作用域时,其值并不丢失。
    本函数没什么用处,因为每次调用时都会将 ¥a 的值设为 0 并输出 0。将变量加一的 ¥a++ 没有作用,因为一旦退出本函数则变量 ¥a 就不存在了。要写一个不会丢失本次计数值的计数函数,要将变量 ¥a 定义为静态的:
    现在,变量 ¥a 仅在第一次调用 test() 函数时被初始化,之后每次调用 test() 函数都会输出 ¥a 的值并加一。

    Another important feature of variable scoping is the static variable. A static variable exists only in a local function scope, but it does not lose its value when program execution leaves this scope. Consider the following example:

    This function is quite useless since every time it is called it sets ¥a to 0 and prints 0. The ¥a++ which increments the variable serves no purpose since as soon as the function exits the ¥a variable disappears. To make a useful counting function which will not lose track of the current count, the ¥a variable is declared static:

    Now, ¥a is initialized only in first call of function and every time the test() function is called it will print the value of ¥a and increment it.

    <?php
    function test()
    {
        static $count = 0;
       // echo $count;
        $count++;
        echo $count;
        if ($count < 10) {
            test();
        }
        echo 'w', $count;
        $count--;
    }
    
    test();
    die();
    test();
    test();
    test();
  • 相关阅读:
    php获取当前月份的前(后)几个月
    javascript实现自动添加文本框功能
    php文件上传系统
    webuploader+文件夹上传
    PHP+实现文件的上传和下载
    java+实现文件的上传和下载
    web文件系统
    php文件夹上传下载控件分享
    asp.net文件夹上传下载控件分享
    java文件夹上传下载控件分享
  • 原文地址:https://www.cnblogs.com/rsapaper/p/6677822.html
Copyright © 2011-2022 走看看