Home Backend Development PHP Tutorial global and $GLOBALS[ in php

global and $GLOBALS[ in php

May 15, 2018 pm 05:07 PM
global php

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

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

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

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

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

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

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

Hot Topics

Java Tutorial
1672
14
PHP Tutorial
1277
29
C# Tutorial
1257
24
PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 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 vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

See all articles