變數分為全域變數和局部變數。學過C語言的童鞋都知道,全域變數的作用域是整個文件。在即使在函數內部也有效,但在php中,如果在函數中使用全域變量,php會認為這個變數沒有定義。如果我們需要在函數內部使用這個全域變量,這時我們就需要在函數內部,這個全域變數前加關鍵字global。下面是自己寫的一個小demo。用來證明我上面說的
<code><span><span><?php</span><span>$str</span> = <span>"string"</span>; <span><span>function</span><span>test</span><span>()</span> {</span><span>if</span> (<span>isset</span>(<span>$str</span>)) { <span>echo</span><span>"the string is defined"</span>; } <span>else</span> { <span>echo</span><span>"the string is undefined"</span>; } } test(); <span>?></span></span></code>
這是在瀏覽器中的運作結果:
the string is undefined
<code><span><span><?php</span><span>$str</span> = <span>"string"</span>; <span><span>function</span><span>test</span><span>()</span> {</span><span>global</span><span>$str</span>;<span>//上面的test函数中没有这句话</span><span>if</span> (<span>isset</span>(<span>$str</span>)) { <span>echo</span><span>"the string is defined"</span>; } <span>else</span> { <span>echo</span><span>"the string is undefined"</span>; } } test(); <span>?></span></span></code>
這是在瀏覽器中的運作結果:
the string is defined
$GLOBALS — 引用全域作用域中可用的全部變數
一個包含了全部變數的全域組合陣列。變數的名字就是數組的鍵。
<code><span><span><?php</span><span><span>function</span><span>test</span><span>()</span> {</span><span>$foo</span> = <span>"local variable"</span>; <span>echo</span><span>'$foo in global scope: '</span> . <span>$GLOBALS</span>[<span>"foo"</span>] . <span>"\n"</span>; <span>echo</span><span>'$foo in current scope: '</span> . <span>$foo</span> . <span>"\n"</span>; } <span>$foo</span> = <span>"Example content"</span>; test(); <span>?></span></span></code>
上述程式的輸出類似:
<code><span>$foo</span><span>in</span><span>global</span> scope: Example content <span>$foo</span><span>in</span> current scope: <span>local</span><span>variable</span></code>').addClass('pre-numbering').hide(); $(this).addClass('has-numbering').parent().append($numbering); for (i = 1; i ').text(i)); }; $numbering.fadeIn(1700); }); });
以上就介紹了 php中global的使用,包括了方面的內容,希望對PHP教程有興趣的朋友有幫助。