search
HomeBackend DevelopmentPHP TutorialAnalysis of the difference between global and $GLOBAL in php

Most people will think that global and $GLOBALS[] are only different in the way they are written, but in fact this is not the case. Let's take a look at the differences between them.

According to the official explanation,

$GLOBALS['var'] is the external global variable $var itself.

global $var is a reference or pointer of the same name as external $var. (Error: It is an alias reference, not a pointer!!!)

Give an example:

Usage of php $GAOBAL[]:

01    <?php    
02    $var1 = 1;    
03    $var2 = 2;    
04    function test() {    
05        $GLOBALS[&#39;var2&#39;] = &$GLOBALS[&#39;var1&#39;];    
06    }    
07    
08    test();    
09    echo $var2;    
10    ?>

The normal print result is 1

Use of php global:

01    <?php    
02    $var1 = 1;    
03    $var2 = 2;    
04    
05    function test(){    
06        global $var1, $var2;    
07        $var2 = &$var1;    
08        echo $var2;    
09        $var2 = &#39;qianyunlai.com&#39;;    
10    }    
11    
12    test(); // 输出 1    
13    echo $var2; // 输出 2    
14    echo $var1; // 输出 qianyunlai.com    
15    ?>

$var1 and $va2 in the test() function are both local variables. They just add the global keyword and refer to the global variable $ respectively. var1, $va2. When $var2 = &$var1;, the local variable $var2 no longer points to the global variable $val2, but redirects to the global variable $var1. In other words, the change of the local variable $var2 does not change. It will then affect the global variable $val2, which will affect the redirected global variable $val1.

Let’s look at another example.

1    <?php    
2    $var1 = 1;    
3    function test(){    
4        unset($GLOBALS[&#39;var1&#39;]);    
5    }    
6    test();    
7    echo $var1;    
8    ?>

Because $var1 was deleted, nothing was printed.

01    <?php    
02    $var1 = 1;    
03    
04    function test(){    
05        global $var1;    
06        unset($var1);    
07    }    
08    
09    test();    
10    echo $var1;    
11    ?>

Accidentally printed 1.

It proves that only the alias is deleted, and the reference of $GLOBALS['var'] has not been changed in any way.

Understand?

In other words, global $var is actually $var = &$GLOBALS['var']. It's just an alias for calling an external variable.

global and $GLOBALS in PHP are not only written differently, but the difference between the two is still very big. You need to pay attention to it in practical applications!

Look at the following example first:

1    <?php    
2    $id = 1;    
3    function test() {    
4        global $id;    
5        unset($id);    
6    }    
7    test();    
8    echo($id); // 输出 1    
9    ?>

Reference positioning

Many PHP syntax structures are implemented through the reference mechanism, so everything above about reference binding also applies to these structures. Some constructs, such as pass-by-reference and return-by-reference, have already been mentioned above. Other structures that use references are:

When you declare a variable with global $var, you actually create a reference to the global variable. That is the same as doing:

01    <?php    
02    $GLOBALS["var1"] = 1;    
03    $var = &$GLOBALS["var1"];    
04    unset($var);    
05    echo $GLOBALS[&#39;var1&#39;]; //输出1    
06    //############################################    
07    $GLOBALS["var1"] = 1;    
08    $var = &$GLOBALS["var1"];    
09    unset($GLOBALS[&#39;var1&#39;]);    
10    echo $var; //输出1    
11    //############################################    
12    //如果写成如下,则会出错    
13    $GLOBALS["var"] = 1;    
14    $var = &$GLOBALS["var"];    
15    unset($GLOBALS[&#39;var&#39;]);    
16    echo $var; //脚本没法执行    
17    //###########################################    
18    ?>

This means that, for example, unset $var will not unset a global variable.

unset just breaks the binding between the variable name and the variable content. This does not mean that the variable contents are destroyed.

Return false when using isset($var). $this In a method of an object, $this is always a reference to the object that calls it.

If a reference is assigned to a variable declared as global inside a function, the reference is only visible inside the function.

This can be avoided by using the $GLOBALS array.

Example to reference global variables within a function:

01    <?php    
02    $var1 = "Example variable";    
03    $var2 = "";    
04    
05    function global_references($use_globals) {    
06        global $var1, $var2;    
07        if (!$use_globals) {    
08            $var2 = &$var1; // visible only inside the function    
09        } else {    
10            $GLOBALS["var2"] = &$var1; // visible also in global context    
11        }    
12    }    
13    
14    global_references(false);    
15    echo "var2 is set to &#39;$var2&#39;\n"; // var2 is set to &#39;&#39;    
16    global_references(true);    
17    echo "var2 is set to &#39;$var2&#39;\n"; // var2 is set to &#39;Example variable&#39;    
18    ?>

Treat global $var; as the abbreviation of $var = &$GLOBALS['var'];. So if you assign another reference to $var, you only change the reference to the local variable.

As mentioned before, references are not pointers. This means that the following construct will not have the expected effect:

1    <?php    
2    $bar = 3;    
3    function foo(&$var) {    
4        $GLOBALS["baz"] = 5;    
5        $var = &$GLOBALS["baz"];    
6    }    
7    foo($bar);    
8    echo $bar;//输出3    
9    ?>

This will cause the $var variable in the foo function to be bound to $bar when the function is called, but then re-bound to $bar $GLOBALS["baz"] above.

It is not possible to bind $bar to other variables in the function call scope through the reference mechanism, because there is no variable $bar in function foo (it is represented as $var, but $var only has variables content without calling the name-to-value binding in the symbol table). You can use reference returns to reference variables selected by the function.

Quoting the explanation of $GLOBALS in the PHP manual:

Global variable: $GLOBALS, note: $GLOBALS is applicable in PHP 3.0.0 and later versions.

An array consisting of all defined global variables. The variable name is the index into the array. This is a "superglobal", or can be described as an automatic global variable.

That is to say, $var1 and $GLOBALS['var1'] in the above code refer to the same variable, not 2 different variables!

If a reference is assigned to a variable declared as global inside a function, the reference is only visible inside the function. This can be avoided by using the $GLOBALS array.

We all know that the variables generated by functions in PHP are private variables of the function, so the variables generated by the global keyword certainly cannot escape this rule. global generates an alias in the function that points to the external variable of the function. variables, rather than real variables external to the function. Once the pointing address of the alias variable is changed, some unexpected situations will occur. $GLOBALS[] is indeed called an external variable, and it will always remain consistent inside and outside the function.

01    <?php    
02    $a = 1;    
03    $b = 2;    
04    function Sum() {    
05        global $a, $b;    
06        $b = $a + $b;    
07    }    
08    Sum();    
09    echo $b;    
10    ?>

The output will be “3″. Global variables $a and $b are declared in the function, and all reference variables of any variable will point to the global variables.

Why is it not 2? Doesn’t it have no effect outside the function? Please note that $b is not modified by reference in the function, but the modified $b points to the value of physical memory, so the external input is 3.

Related recommendations:

PHP Global and $GLOBALS variable scope and differences

The above is the detailed content of Analysis of the difference between global and $GLOBAL in php. For more information, please follow other related articles on the PHP Chinese website!

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
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

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

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

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.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)