Variables are divided into global variables and local variables. Anyone who has learned C language knows that the scope of global variables is the entire file. It is valid even inside a function, but in PHP, if you use a global variable in a function, PHP will think that the variable is not defined. If we need to use this global variable inside the function, then we need to add the keyword global before the global variable inside the function. Below is a small demo I wrote. To prove what I said above
<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>
This is the result of running in the browser:
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>
This is the result of running in the browser:
the string is defined
$GLOBALS — a reference to all variables available in the global scope
A global combined array containing all variables. The name of the variable is the key of the array.
<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>
The output of the above routine is similar to:
<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>
The above introduces the use of global in PHP, including aspects of it. I hope it will be helpful to friends who are interested in PHP tutorials.