Maison > Article > développement back-end > php的静态局部变量
静态局部变量可以做到,该变量和全局变量保存在内存中同一区域,但是我们离开了声明该静态局部变量函数却不能访问到该变量,但是该变量并没有被销毁,它的值得到了保留。再次调用函数时它就再次可以访问到,需要注意的是:
1.静态局部变量声明时不能是表达式,是表达式会出错
<code><span>static</span><span>$index</span> = <span>1</span>; <span>static</span><span>$index</span> = <span>5</span>; <span>// 报错</span></code>
2.赋值静态变量时不能使用表达式
<code><span>static</span><span>$index</span> = <span>1</span> + <span>1</span>; <span>// 报错</span></code>
3.如果我们只是声明了一个局部变量并没有赋值的化,会默认为其初始化一个0或者空字符串,根据其类型来确定到底是0还是空字符串
例子:
将数组降维(降到一维)
<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>').addClass('pre-numbering').hide(); $(this).addClass('has-numbering').parent().append($numbering); for (i = 1; i ').text(i)); }; $numbering.fadeIn(1700); }); });
以上就介绍了php的静态局部变量,包括了全局变量,静态变量方面的内容,希望对PHP教程有兴趣的朋友有所帮助。