靜態局部變數可以做到,該變數和全域變數保存在記憶體中同一區域,但是我們離開了聲明該靜態局部變數函數卻不能存取到該變量,但是該變數並沒有被銷毀,它的值得到了保留。再次呼叫函數時它就再次可以存取到,需要注意的是:
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>
以上就介紹了php的靜態局部變量,包含了全域變數,靜態變數方面的內容,希望對PHP教學有興趣的朋友有幫助。