search
HomeBackend DevelopmentPHP TutorialDetailed explanation of global variables in PHP_PHP tutorial

Detailed explanation of global variables in PHP_PHP tutorial

Jul 13, 2016 pm 05:14 PM
globalphpintroduceoverall situationaboutvariablearticleofDetailed explanation

This article will introduce in detail the method of global variable global in PHP. Friends who need to know how to use the global function can refer to this article.

The scope of a variable is the context in which it is defined (that is, its effective scope). Most PHP variables have only a single scope. This single scope span also includes files introduced by include and require. For example:

The code is as follows Copy code
 代码如下 复制代码

$a = 1;
include 'b.inc';
?>

$a = 1;
include 'b.inc';
?>

This variable $a will take effect in the included file b.inc. However, in user-defined functions, a local function scope will be introduced. Any variables used inside a function will be restricted to the local function scope by default. For example:
 代码如下 复制代码

$a = 1; /* global scope */

function Test()
{
    echo $a; /* reference to local scope variable */
}

Test();
?>

The code is as follows Copy code

$a = 1; /* global scope */

function Test()
{
echo $a; /* reference to local scope variable */
}

Test();
?>

 代码如下 复制代码
$a = 0 ;
function Test()
{
    $a =1;
}
Test();
echo $a;
?>
This script will produce no output because the echo statement refers to a local version of the variable $a, and it is not assigned a value within this scope. You may notice that PHP's global variables are a little different from C language. In C language, global variables automatically take effect in functions unless overridden by local variables. This may cause some problems, someone may accidentally change a global variable. Global variables in PHP must be declared global when used in functions.

Today I encountered the problem that php global variables do not work.
 代码如下 复制代码
$a = 0 ;
function Test()
{
    global $a;//申明函数体Test内使用的$a变量为global全局变量
    $a =1;
}
Test();
echo $a;
?>
First a simple piece of code: The output in the above code is 0, that is because the $a variable in the function body Test is set to a local variable by default, and the scope of $a is within Test. Modify the code as follows

After declaring the $a variable used in the function body Test as a global global variable, $a has a global effect, so the output is 1.
The above examples are just basic knowledge of global variables. Let’s look at more complicated ones:

//A.php file

//B.php file
The code is as follows
 代码如下 复制代码

function Test_Global()
{  
    include 'B.php';  
    Test();  
}  

$a = 0 ;
Test_Global();
echo $a;
?> 

//B.php 文件

function Test()
{
    global $a;//申明函数体Sum内使用的$a变量为global全局变量
    $a =1;
}
?>

Copy code

function Test_Global()

{  

Include 'B.php';  

Test();  

}  

 代码如下 复制代码

//A.php 文件

function Test_Global()
{  
    Test();  
}  
include 'B.php';   //将include 从局部Test_Global函数中移出
$a = 0 ;
Test_Global();
echo $a;
?> 

//B.php 文件

function Test()
{
    global $a;
    $a =1;
}
?>

$a = 0 ;

Test_Global();

echo $a;
 代码如下 复制代码

//A.php 文件
include 'B.php'; 
$a =0;
Set_Global($a);
echo $a;
?> 

//B.php 文件

function Set_Global(&$var)
{
    $var=1;
}
?>

?> 
function Test()
{   $a =1; } ?> Why is the output 0?!! In user-defined functions, a local function scope will be introduced. Any variables used inside a 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 global variable of $a in the B.php file, so $a is limited to the Test_Global local function scope, so B The scope of $a in the .php file is within Test_Global, instead of affecting the entire A.php....
Solution:
1. Break out of local function
The code is as follows Copy code
//A.php file 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
The code is as follows Copy code
//A.php file include 'B.php';  $a =0; Set_Global($a); echo $a; ?>  //B.php file function Set_Global(&$var) { $var=1; } ?> http://www.bkjia.com/PHPjc/628915.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/628915.htmlTechArticleThis article will introduce in detail the method of global variable global in PHP. Friends who need to know how to use the global function You can refer to this article. The scope of a variable is the context in which it is defined...
Statement
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
Explain the concept of session locking.Explain the concept of session locking.Apr 29, 2025 am 12:39 AM

Sessionlockingisatechniqueusedtoensureauser'ssessionremainsexclusivetooneuseratatime.Itiscrucialforpreventingdatacorruptionandsecuritybreachesinmulti-userapplications.Sessionlockingisimplementedusingserver-sidelockingmechanisms,suchasReentrantLockinJ

Are there any alternatives to PHP sessions?Are there any alternatives to PHP sessions?Apr 29, 2025 am 12:36 AM

Alternatives to PHP sessions include Cookies, Token-based Authentication, Database-based Sessions, and Redis/Memcached. 1.Cookies manage sessions by storing data on the client, which is simple but low in security. 2.Token-based Authentication uses tokens to verify users, which is highly secure but requires additional logic. 3.Database-basedSessions stores data in the database, which has good scalability but may affect performance. 4. Redis/Memcached uses distributed cache to improve performance and scalability, but requires additional matching

What is the full form of PHP?What is the full form of PHP?Apr 28, 2025 pm 04:58 PM

The article discusses PHP, detailing its full form, main uses in web development, comparison with Python and Java, and its ease of learning for beginners.

How does PHP handle form data?How does PHP handle form data?Apr 28, 2025 pm 04:57 PM

PHP handles form data using $\_POST and $\_GET superglobals, with security ensured through validation, sanitization, and secure database interactions.

What is the difference between PHP and ASP.NET?What is the difference between PHP and ASP.NET?Apr 28, 2025 pm 04:56 PM

The article compares PHP and ASP.NET, focusing on their suitability for large-scale web applications, performance differences, and security features. Both are viable for large projects, but PHP is open-source and platform-independent, while ASP.NET,

Is PHP a case-sensitive language?Is PHP a case-sensitive language?Apr 28, 2025 pm 04:55 PM

PHP's case sensitivity varies: functions are insensitive, while variables and classes are sensitive. Best practices include consistent naming and using case-insensitive functions for comparisons.

How do you redirect a page in PHP?How do you redirect a page in PHP?Apr 28, 2025 pm 04:54 PM

The article discusses various methods for page redirection in PHP, focusing on the header() function and addressing common issues like "headers already sent" errors.

Explain type hinting in PHPExplain type hinting in PHPApr 28, 2025 pm 04:52 PM

Article discusses type hinting in PHP, a feature for specifying expected data types in functions. Main issue is improving code quality and readability through type enforcement.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.