Home  >  Article  >  Backend Development  >  The difference between global and $GLOBALS in PHP

The difference between global and $GLOBALS in PHP

藏色散人
藏色散人forward
2019-10-25 13:37:442269browse

Concept

A single global is a keyword, usually attached before a variable, used to declare the variable to the global scope;

$GLOBALS is a pre- If you throw the defined super global variable into it, it can also be brought to the global world.

$GLOBALS is an associative array, each variable is an element, the key name corresponds to the variable name, and the value corresponds to the content of the variable. $GLOBALS exists in the global scope because $GLOBALS is a superglobal variable.

Recommended: "PHP Video Tutorial"

Details: Notes on releasing global variables in PHP

global $var: refers to Reference to a variable with the same name outside the function

$GLOBALS['var']: refers to the variable outside the function itself

$a = 100;
function one(){
    global $a;
    unset($a);
}
one();
echo $a;
// 输出 100
/*******************************/
$a = 100;
function two(){
    unset($GLOBALS['a']);
}
two();
echo $a;
// 输出 Notice: Undefined variable: a

global $var; Equivalent to $var = &$GLOBALS['var'] ;

To release a global variable within a function, it should look like this:

unset($GLOBALS['var']);

but not like this:

global $var; unset($var);
<?php
$var = &#39;abc&#39;;
$tmp = &$var;
unset($tmp); //当你unset一个引用,只是断开了变量名和变量内容之间的绑定,这并不意味着变量内容被销毁了.
echo $var; //输出abc

The above is the detailed content of The difference between global and $GLOBALS in PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete