For PHP beginners, when using the global
keyword , you may find that a variable outside the function global
cannot be output 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 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 !"; } ?>
a.php page 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, the welcome can be displayed correctly statement. However, unfortunately, when we use the browser to access the a.php page, we find the following output:
Hello! Welcome to !
That is to say, we call it in the function include_view_page()
When using the sayHi()
function, the $site_name
in the global
function of the b.php page was not correctly recognized and took effect. What exactly is this matter about?
include b.php page in function include_view_page()
, the variable $site_name
of b.php page is equivalent to the function stored in include_view_page()
in the domain. As we all know, a variable within a function global
actually establishes a reference to the global variable of the page within the function. In our example, this $site_name
variable is just a local variable within the include_view_page()
function for a.php, so it cannot be global
. Naturally, we cannot get it when we make related calls. Correct variables and variable values.
include a certain page within a function, causing the scope of the variables in the page to change. In order to avoid this situation, we should try to reduce multiple levels of include
calls and try not to use include
within functions.
This failure is caused by many reasons. An effective solution is to use the $GLOBALSarray which is always valid:
$GLOBALS['site_name'] = 'CodePlayer';
The above introduces the invalid php global variables, including aspects of the content. I hope it will be helpful to friends who are interested in PHP tutorials.