Home  >  Article  >  Backend Development  >  Static local variables in php

Static local variables in php

WBOY
WBOYOriginal
2016-07-29 09:13:461537browse

Static local variables can do this. This variable and global variable are stored in the same area of ​​memory, but we cannot access the variable without the function that declares the static local variable, but the variable has not been destroyed. Worthy of preservation. When the function is called again, it will be accessible again. Note that:
1. When declaring a static local variable, it cannot be an expression. If it is an expression, an error will occur

static$index = 1;
static$index = 5;  // 报错

2. When assigning a valuestatic variable, you cannot use an expression

static$index = 1 + 1;  // 报错

3. If we just declare a local variable without assigning a value, , will initialize it with a 0 or an empty string by default, and determine whether it is 0 or an empty string according to its type

Example:
Reduce the dimension of the array (to one dimension)

classTest{publicfunctionreduce_arr($arr) {static$temp = array(); // 声明了一个静态局部变量foreach ($arras$key => $val) {
            if (is_array($val)) {
                $this->reduce_arr($val);
            } else {
                $temp[$key] = $val;
            }
        }
        return$temp;
    }
}
$test = new Test();
$arr = array(
    '0'=>array(
        'good_id'=>1
    ),
    '1'=>array(
        'good_num'=>2
    ),
    '2'=>array(
        'good_ids'=>2
    )
);
var_dump($test->reduce_arr($arr));  // 此时得到的是一个一维数组
').addClass('pre-numbering').hide(); $(this).addClass('has-numbering').parent().append($numbering); for (i = 1; i ').text(i)); }; $numbering.fadeIn(1700); }); });

The above introduces the static local variables of PHP, including global variables and static variables. I hope it will be helpful to friends who are interested in PHP tutorials.

Statement:
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