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
PHP Performance Tuning for High Traffic WebsitesPHP Performance Tuning for High Traffic WebsitesMay 14, 2025 am 12:13 AM

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

Dependency Injection in PHP: Code Examples for BeginnersDependency Injection in PHP: Code Examples for BeginnersMay 14, 2025 am 12:08 AM

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

PHP Performance: is it possible to optimize the application?PHP Performance: is it possible to optimize the application?May 14, 2025 am 12:04 AM

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

PHP Performance Optimization: The Ultimate GuidePHP Performance Optimization: The Ultimate GuideMay 14, 2025 am 12:02 AM

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

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 Article

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.

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

SublimeText3 Chinese version

Chinese version, very easy to use

EditPlus Chinese cracked version

EditPlus Chinese cracked version

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

Atom editor mac version download

Atom editor mac version download

The most popular open source editor