Home Backend Development PHP Tutorial Analysis of the difference between global and $GLOBAL in php

Analysis of the difference between global and $GLOBAL in php

Jul 18, 2018 am 11:48 AM

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    ?>
Copy after login

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    ?>
Copy after login

$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    ?>
Copy after login

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    ?>
Copy after login

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    ?>
Copy after login

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    ?>
Copy after login

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    ?>
Copy after login

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    ?>
Copy after login

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    ?>
Copy after login

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 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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

How does session hijacking work and how can you mitigate it in PHP? How does session hijacking work and how can you mitigate it in PHP? Apr 06, 2025 am 12:02 AM

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

What are Enumerations (Enums) in PHP 8.1? What are Enumerations (Enums) in PHP 8.1? Apr 03, 2025 am 12:05 AM

The enumeration function in PHP8.1 enhances the clarity and type safety of the code by defining named constants. 1) Enumerations can be integers, strings or objects, improving code readability and type safety. 2) Enumeration is based on class and supports object-oriented features such as traversal and reflection. 3) Enumeration can be used for comparison and assignment to ensure type safety. 4) Enumeration supports adding methods to implement complex logic. 5) Strict type checking and error handling can avoid common errors. 6) Enumeration reduces magic value and improves maintainability, but pay attention to performance optimization.

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How to debug CLI mode in PHPStorm? How to debug CLI mode in PHPStorm? Apr 01, 2025 pm 02:57 PM

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

How to send a POST request containing JSON data using PHP's cURL library? How to send a POST request containing JSON data using PHP's cURL library? Apr 01, 2025 pm 03:12 PM

Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

See all articles