Analysis 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['var2'] = &$GLOBALS['var1']; 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 = 'qianyunlai.com'; 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['var1']); 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['var1']; //输出1 06 //############################################ 07 $GLOBALS["var1"] = 1; 08 $var = &$GLOBALS["var1"]; 09 unset($GLOBALS['var1']); 10 echo $var; //输出1 11 //############################################ 12 //如果写成如下,则会出错 13 $GLOBALS["var"] = 1; 14 $var = &$GLOBALS["var"]; 15 unset($GLOBALS['var']); 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 '$var2'\n"; // var2 is set to '' 16 global_references(true); 17 echo "var2 is set to '$var2'\n"; // var2 is set to 'Example variable' 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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Alipay PHP...

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,

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.

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.

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? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

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

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.
