PHP’s global variables are different from other programming languages. In most programming languages, global variables automatically take effect in the functions and classes below them, unless they are overridden by local variables, or they are not allowed to be declared with the same name at all. Type of local variables, but global variables in php are not effective by default. Global variables in PHP must be declared global when used in functions. The Global keyword is only useful when defined in functions. In other words, the role of Global is to define global variables, but this global variable does not apply to the entire website, but to the current page, including all files in include or require.
Use an example directly to illustrate this problem, the following code:
<?php $a=5; function test(){ echo $a; } test(); ?>
An error is reported directly. It is simply unreasonable to say that a is not defined, but PHP is set up like this, but I need to use $a as a global variable. There may be many functions and classes below that need to use this $a! This is, you need to declare it with the global keyword every time you use the global variable $a.
The following code is a correct demonstration:
<?php $a=5; function test(){ global $a; echo $a; } test(); ?>
It is worth noting that the following code is wrong:
<?php global $a; $a=5; function test(){ echo $a; } test(); ?>
Copyright statement: This article is an original article by the blogger and may not be reproduced without the blogger's permission.
The above introduces the use of global and the global variables of PHP, including the relevant content. I hope it will be helpful to friends who are interested in PHP tutorials.