变量分为全局变量和局部变量。学过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></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></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></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>
以上就介绍了 php中global的使用,包括了方面的内容,希望对PHP教程有兴趣的朋友有所帮助。