For beginners in PHP, when using the global keyword, you may find that a variable outside of a function within a function, in some cases, does not output the variable correctly (that is, the global variable is invalid). Let's look at a simple and common example.
Here we have the a.php and b.php two pages.
The b.php page code is as follows:
| The 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:
| The code is as follows |
|
|
<?php
function Include_view_page () {
Include ' b.php ';
Sayhi ();
}
Include_view_page ();
?> |
The above example is very simple, we hope that when we visit the a.php page, we can display the welcome statement correctly. Unfortunately, however, when we accessed the a.php page using a browser, we found that the output was as follows:
Hello! Welcome to!
In other words, when we call the Sayhi () function in the function include_view_page (), the $site_name of global in the b.php page Sayhi () function is not recognized correctly and takes effect. What the hell is this all about?
In fact, when we include a b.php page in the function include_view_page (), the b.php page's variable $site_name is stored in the scope within the Include_view_page () function. As we all know, a variable in a function is actually a reference to a page global variable within a function. In our case, the $site_name variable for a.php is just a local variable within the Include_view_page () function, so the variable cannot be global, and we naturally cannot get the correct variable and variable value when we make the related call.
In PHP, we particularly need to be aware of the problem of having a page in a function like the one above, causing the variable's scope to change in the page. To avoid this, we should minimize the multi-level include invocation and try not to use include within the function. In addition, we can make declarations in the form of global variables in the b.php page. $site_name
| The code is as follows |
|
|
b.php
<?php
Global $site _name;
$site _name = ' Codeplayer ';
function Sayhi () {
Global $site _name;
echo "hello! Welcome to $site _name! ";
}
?> |
example, reference global variables within a function
First look at the following code:
| The code is as follows |
|
|
<?php
$var 1 = "#####";
$var 2 = "&&&&&";
function global_references ($use _globals)
{
Global $var 1, $var 2;
if (! $use _globals) {
$var 2 =& $var 1; 1
} else {
$GLOBALS ["Var2"] =& $var 1; 2
}
}
Global_references (FALSE);
echo "VAR2 is set to ' $var 2 ' <br/>";
Global_references (TRUE);
echo "VAR2 is set to ' $var 2 ' <br/>";
?> |
The results of the output are as follows:
VAR2 is set to ' &&&&& '
VAR2 is set to ' ##### '
Visible, in the above code:
$var 2 =& $var 1; 1
Visible only within the function.
and
$GLOBALS ["Var2"] =& $var 1; 2
Visible in the global scope.