PHP's global variables and the rest of the programming language are different, in most programming languages, the global variable under its function, the class automatically take effect, unless overridden by a local variable, or do not allow the declaration of the same name and type of local variables, but the global variables in PHP is not in effect by default. In PHP, global variables must be declared global when used in functions, and global is only useful when defined in a function. In other words, global is defined as globally variable, but this global variable is not applied to the entire site, but applies to the current page, including all files of include or require.
To illustrate this problem directly with an example, the following code:
Very simply, declare a global variable $a=5, and then declare a function test () to print the global variable, then call the test (), according to the General programming language thinking, here the output must be 5, however, in the actual implementation is the following effect:
Direct error, said that a no definition, it is not unreasonable, but PHP is set, but I need to use a $ A as a global variable, there may be a lot of functions, many classes to use this $ A ah! This is, you need to use the global variable $ A each time to declare it with global keyword.
The following code is the correct demonstration:
The result is as follows, so that a can be used, each time you use the global variable $ A to declare it, this is the PHP rule.
It is important to note that the following code is wrong:
The same goes for the running result:
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.