Instructions for using PHP Global to define global variables_PHP tutorial

WBOY
Release: 2016-07-21 14:59:14
Original
1201 people have browsed it

I am not 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:

Copy code The code is as follows:

$test = 123;
abc() ; //Nothing is output here because the $test variable cannot be accessed
function abc(){
echo($test);
}$test = 123;
abc(); / /Nothing is output here because the $test variable cannot be accessed
function abc(){
echo($test);
}

If, you want to use To access external variables internally, you need to do this:
Copy the code The code is as follows:

$test = 123;
abc (); //Output 123
function abc(){
global $test;
echo($test);
}$test = 123;
abc(); //Output 123
function abc(){
global $test;
echo($test);
}

But what if we define global variables in the function, like The following is as follows:
Copy the code The code is as follows:

function abc(){
global $test;
$test = 123;
}
abc();
echo($test); //Output 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 user-defined functions, 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: Test_Global in the A.php file is a defined third party Function, this function uses include to import the global variable of $a in the B.php file, so $a is limited to the scope of the Test_Global local function, so the scope of $a in the B.php file is within Test_Global. Instead of affecting the entire A.php...
Solution:
1. Break out the local function
//A.php file
Copy code The code is as follows:

function Test_Global()
{
Test();
}
include 'B. php'; //Move include from the local Test_Global function
$a = 0;
Test_Global();
echo $a;
?>
//B.php file
function Test()
{
global $a;
$a =1;
}
?>

2. Excellent accessor
Copy code The code is as follows:

//A.php file
< ;?php
include 'B.php';
$a =0;
Set_Global($a);
echo $a;
?>
//B. php file
function Set_Global(&$var)
{
$var=1;
}
?>

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/328173.htmlTechArticleI am not used to the variable scope in PHP. Function variables in PHP are completely isolated from the global world, that is, they cannot mutual access. For example, as follows: Copy code The code is as follows: $test = 123; a...
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template