For beginners in PHP, global
when using a keyword, you might find that global
a variable outside of a function in a function cannot output the variable correctly in some cases (that is, the global
variable is invalid). Let's look at a simple and common example.
Here we have two pages of a.php and b.php.
The b.php page code is as follows:
- <? PHP
- $site _name = ' Codeplayer ' ;
- function Sayhi (){
- Global $site _name;
- Echo "hello! Welcome to $site _name! " ;
- }
- ?>
The a.php page code is as follows:
- <? PHP
- function Include_view_page (){
- include ' b.php ' ;
- Sayhi ();
- }
- Include_view_page ();
- ?>
The example above is very simple and we want to be able to display the welcome statement correctly when we visit the a.php page. However, unfortunately, when we use the browser to access the a.php page, we find that the output is as follows:
Hello! Welcome to!
In other words, when we call a function in a function include_view_page()
sayHi()
, the b.php page sayHi()
function is global
$site_name
not correctly recognized and effective. What the hell is going on here?
In fact, when we b.php a page in a function, the variable on the include_view_page()
include
b.php page is equivalent to the scope $site_name
include_view_page()
within the function. It is well known that within global
a function a variable actually establishes a reference to a page global variable within a function. In our case, this $site_name
variable is only a local variable within the function for a.php, so it is include_view_page()
not possible for the variable to get the global
correct variable and variable value when we make the related call.
In PHP, we need to pay particular attention to the problem of include
changing the scope of variables in the page, which is similar to the one in the function above. To avoid this, we should try to minimize the number of include
calls and try not to use them within the function include
. In addition, we can declare $site_name in the form of a global variable on the b.php page.
- //b.php
- < ? php
- global $site _name
- $site _name = ' Codeplayer '
-
- function Sayhi () {
- global $site _name ;
- echo "hello! Welcome to $site _name! "
- }
- ?>
turn from: http://www.365mini.com/page/php-global-invalid.htm