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
<code><span>static</span><span>$index</span> = <span>1</span>; <span>static</span><span>$index</span> = <span>5</span>; <span>// 报错</span></code>
2. When assigning a valuestatic variable, you cannot use an expression
<code><span>static</span><span>$index</span> = <span>1</span> + <span>1</span>; <span>// 报错</span></code>
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)
<code><span><span>class</span><span>Test</span>{</span><span>public</span><span><span>function</span><span>reduce_arr</span><span>(<span>$arr</span>)</span> {</span><span>static</span><span>$temp</span> = <span>array</span>(); <span>// 声明了一个静态局部变量</span><span>foreach</span> (<span>$arr</span><span>as</span><span>$key</span> => <span>$val</span>) { <span>if</span> (is_array(<span>$val</span>)) { <span>$this</span>->reduce_arr(<span>$val</span>); } <span>else</span> { <span>$temp</span>[<span>$key</span>] = <span>$val</span>; } } <span>return</span><span>$temp</span>; } } <span>$test</span> = <span>new</span> Test(); <span>$arr</span> = <span>array</span>( <span>'0'</span>=><span>array</span>( <span>'good_id'</span>=><span>1</span> ), <span>'1'</span>=><span>array</span>( <span>'good_num'</span>=><span>2</span> ), <span>'2'</span>=><span>array</span>( <span>'good_ids'</span>=><span>2</span> ) ); var_dump(<span>$test</span>->reduce_arr(<span>$arr</span>)); <span>// 此时得到的是一个一维数组</span></code>
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.