search
HomeBackend DevelopmentPHP Tutorialglobal and $GLOBALS[ in php

global and $GLOBALS[ in php

May 15, 2018 pm 05:07 PM
globalphp

This article mainly introduces the difference between global and $GLOBALS[' '] in php. Interested friends can refer to it. I hope it will be helpful to everyone.

I always thought that there was no difference between global and $GLOBALS[' '] in php. I checked it today and found that there is a big difference between the two. I made the following summary:
global $var: It is a reference to the global variable $var;
$GLOBALS["var"]: It is the global variable $var itself, which is equivalent to $var.
Here are a few examples:
Example 1:

<?php
    $var1 = 1;    
    $var2 = 2;    
    function test() {
        $GLOBALS[&#39;var2&#39;] = &$GLOBALS[&#39;var1&#39;];
    }
    test();   
    echo $var2;//输出1
?>

test() function $GLOBALS['var2'] is equivalent to the global variable $var1,
$GLOBALS['var2'] = $GLOBALS['var1'] functions to change $var2 is a reference to $var1, that is, $var2 is an alias of $var1, and both point to the same memory space, so the value of \$var2 becomes 1.

Example 2:

<?php
    $var1 = 1;    
    $var2 = 2;    
    function test(){
        global $var1, $var2;        
        $var2 = &$var1;        
        echo $var2;        
        $var2 = &#39;hello...&#39;;
    }
    test(); // 输出 1
    echo $var2; // 输出 2
    echo $var1; // 输出 hello...
?>

In the test function, $var1 and $var2 are references (ie aliases) to the global variables $var1 and $var2 respectively
$var2 = &$var1; //The value of $var2 (local variable) in the test function is changed to the reference of $var1 in the function
At this time, the value of $var2 in the test function is equal to the value of $var1 in the function, which is also equal to the global variable The value of $var1, all three point to the same memory space. When the value of $var2 in the test function changes, the values ​​of the other two ($var1 in the test function and $var1 in the global variable) also change. Variety.

Example 3.

<?php
    $var1 = 1;    
    function test(){
        unset($GLOBALS[&#39;var1&#39;]);
    }
    test();    
    echo $var1;
?>

As mentioned above, $GLOBALS['var1'] is equivalent to $var1 in global variables, unset($GLOBALS['var1' ] ); is equivalent to destroying the global variable $var1, so printing is empty
Supplement:
The unset() function in php is used to destroy variables. In many cases, it just destroys the variable, but in the memory The value is not destroyed (that is, the unset() function exponentially cuts off the relationship between the variable and the memory, destroys the variable name, the value in the memory is not destroyed, and the memory is not released). What needs to be noted is:
1. This function will only release the memory when the memory occupied by the variable exceeds 256 bytes.
2. The address will be released only when all variables pointing to the memory pointed to by the variable (such as all references to the variable) are destroyed.

Example 4.

<?php
    $var1 = 1;    
    function test(){
        global $var1;        
        unset($var1);
    }
    test(); 
    echo $var1; //结果为打印1
?>

In this code, the variable defined using global in the test() function is actually just a reference to the global variable $var, which is destroyed in the test() function This variable is equivalent to destroying a reference to the global variable (a piece of memory has two names. Deleting one of the names will not affect the other name and the value of the memory). Therefore, when printing the global variable $var, the result is still 1. The operation of this code is similar to the following code:

<?php
    $var = 1;    
    $var1 = &$var;    
    unset($var1);    
    echo $var;
?>

Look at another example of referencing global variables inside a function:

<?php
    $var1 = "我是变量var1的值";    
    $var2 = "我是变量var2的值";    
    function global_references($use_globals) {
        global $var1, $var2;        
        if (!$use_globals) {            
        $var2 = &$var1;            
        echo $var1;            
        echo $var2;            
        echo "<br />";
        } else {            
        $GLOBALS["var2"] = &$var1;            
        echo $var1;            
        echo $var2;            
        echo "<br />";
        }
    }
    global_references(false);
    //1.打印:我是变量var1的值我是变量var1的值
    echo $var1;    
    echo $var2;    
    echo "<br />"; 
    //2.打印:我是变量var1的值我是变量var2的值

    global_references(true); 
    //3.打印:我是变量var1的值我是变量var2的值
    echo $var1;    
    echo $var2;    
    echo "<br />"; 
    //4.打印:我是变量var1的值我是变量var1的值
?>
  1. Because the parameters are false, so the statement in the if is executed, and the value of var2 declared in the global_references() function, which was originally a reference to the global variable var2, becomes a reference to var1, so the two variables printed in the global_references() function are both of the global variable var1. Quote.

  2. 1 The executed statement does not affect the value of the global variable, so the value declared at the beginning of the program is printed.

  3. Because the parameter is true, the statement in else is executed to change the value of global variable var1 to the reference of global variable var1 (var1 declared in the global_references() function). This does not change the value of var2 declared in global_references() (it is still a reference to the original memory).

  4. After 3, the global variable var2 has become a reference to the global variable var1, so the values ​​of the two global variables are the same at this time.

Summary:
global $var: is a reference to the global variable $var;
$GLOBALS["var"]: is the global variable $var itself, that is Equivalent to $var.
If the former is a variable declared inside a function, its scope is the function, that is, it is only visible within the function. This variable is a reference to a global variable. Destroying the variable will not affect the function. The global variable it points to has an impact.

Related recommendations:

PHP reads external variable $GLOBALS

Cause of PHP json_encode($GLOBALS) error

const and global in php

The above is the detailed content of global and $GLOBALS[ 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
How can you protect against Cross-Site Scripting (XSS) attacks related to sessions?How can you protect against Cross-Site Scripting (XSS) attacks related to sessions?Apr 23, 2025 am 12:16 AM

To protect the application from session-related XSS attacks, the following measures are required: 1. Set the HttpOnly and Secure flags to protect the session cookies. 2. Export codes for all user inputs. 3. Implement content security policy (CSP) to limit script sources. Through these policies, session-related XSS attacks can be effectively protected and user data can be ensured.

How can you optimize PHP session performance?How can you optimize PHP session performance?Apr 23, 2025 am 12:13 AM

Methods to optimize PHP session performance include: 1. Delay session start, 2. Use database to store sessions, 3. Compress session data, 4. Manage session life cycle, and 5. Implement session sharing. These strategies can significantly improve the efficiency of applications in high concurrency environments.

What is the session.gc_maxlifetime configuration setting?What is the session.gc_maxlifetime configuration setting?Apr 23, 2025 am 12:10 AM

Thesession.gc_maxlifetimesettinginPHPdeterminesthelifespanofsessiondata,setinseconds.1)It'sconfiguredinphp.iniorviaini_set().2)Abalanceisneededtoavoidperformanceissuesandunexpectedlogouts.3)PHP'sgarbagecollectionisprobabilistic,influencedbygc_probabi

How do you configure the session name in PHP?How do you configure the session name in PHP?Apr 23, 2025 am 12:08 AM

In PHP, you can use the session_name() function to configure the session name. The specific steps are as follows: 1. Use the session_name() function to set the session name, such as session_name("my_session"). 2. After setting the session name, call session_start() to start the session. Configuring session names can avoid session data conflicts between multiple applications and enhance security, but pay attention to the uniqueness, security, length and setting timing of session names.

How often should you regenerate session IDs?How often should you regenerate session IDs?Apr 23, 2025 am 12:03 AM

The session ID should be regenerated regularly at login, before sensitive operations, and every 30 minutes. 1. Regenerate the session ID when logging in to prevent session fixed attacks. 2. Regenerate before sensitive operations to improve safety. 3. Regular regeneration reduces long-term utilization risks, but the user experience needs to be weighed.

How do you set the session cookie parameters in PHP?How do you set the session cookie parameters in PHP?Apr 22, 2025 pm 05:33 PM

Setting session cookie parameters in PHP can be achieved through the session_set_cookie_params() function. 1) Use this function to set parameters, such as expiration time, path, domain name, security flag, etc.; 2) Call session_start() to make the parameters take effect; 3) Dynamically adjust parameters according to needs, such as user login status; 4) Pay attention to setting secure and httponly flags to improve security.

What is the main purpose of using sessions in PHP?What is the main purpose of using sessions in PHP?Apr 22, 2025 pm 05:25 PM

The main purpose of using sessions in PHP is to maintain the status of the user between different pages. 1) The session is started through the session_start() function, creating a unique session ID and storing it in the user cookie. 2) Session data is saved on the server, allowing data to be passed between different requests, such as login status and shopping cart content.

How can you share sessions across subdomains?How can you share sessions across subdomains?Apr 22, 2025 pm 05:21 PM

How to share a session between subdomains? Implemented by setting session cookies for common domain names. 1. Set the domain of the session cookie to .example.com on the server side. 2. Choose the appropriate session storage method, such as memory, database or distributed cache. 3. Pass the session ID through cookies, and the server retrieves and updates the session data based on the ID.

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

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

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.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.