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

The difference between global and $GLOBALS in PHP

藏色散人
Release: 2023-04-07 17:56:01
forward
2366 people have browsed it

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

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

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

unset($GLOBALS['var']);
Copy after login

but not like this:

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

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!

Related labels:
source:segmentfault.com
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template