Global is a special command in php. We just call it super global variable. Now let me introduce how I used Global to define global study notes today.
It’s very strange. Get used to the variable scope in PHP. In PHP, function variables and the global world are completely isolated, that is, they cannot access each other.
For example:
The code is as follows:
$test = 123; abc(); //这里什么都不输出,因为访问不到$test变量 function abc(){ echo($test); }$test = 123; abc(); //这里什么都不输出,因为访问不到$test变量 function abc(){ echo($test); }
If you want to access external variables inside the function, you need to do this:
The code is as follows:
$test = 123; abc(); //输出123 function abc(){ global $test; echo($test); }$test = 123; abc(); //输出123 function abc(){ global $test; echo($test); }
But what if we define global variables in the function, like the following:
The code is as follows:
function abc(){ global $test; $test = 123; } abc(); echo($test); //输出123function abc(){ global $test; $test = 123; } abc(); echo($test);
//Output 123
In this way, we can access the variables defined inside the function from the outside
In the user custom function, a local function scope will be introduced. Any variables used inside the function will be limited to the local function scope by default (including variables in files imported by include and require)!
Explanation: A Test_Global in the .php file is a defined third-party function. This function uses include to import the global global variable of $a in the B.php file, so $a is limited to the scope of the Test_Global local function, so the B.php file The scope of $a in Test_Global is within Test_Global, instead of affecting the entire A.php...
Solution:
1. Break out of the local function
//A.php file
The code is as follows:
<?php function Test_Global() { Test(); } include 'B.php'; //将include 从局部Test_Global函数中移出 $a = 0 ; Test_Global(); echo $a; ?> //B.php 文件 <?php function Test() { global $a; $a =1; } ?>
2. Excellent accessor
The code is as follows:
//A.php file
<?php include 'B.php'; $a =0; Set_Global($a); echo $a; ?> //B.php 文件 <?php function Set_Global(&$var) { $var=1; } ?>
The above is the detailed content of How to define global variables in php?. For more information, please follow other related articles on the PHP Chinese website!