关于PHP中的全局变量global和$GLOBALS的不同区分 - WORSHIP亚萨

一个新手
Release: 2023-03-16 13:50:02
Original
1263 people have browsed it

1.global

  Global的作用是定义全局变量,但是这个全局变量不是应用于整个网站,而是应用于当前页面,包括include或require的所有文件。

  但是在函数体内定义的global变量,函数体内可以使用,在函数体外定义的global变量不能在函数体内使用,具体看下面示例。

(1)在函数体内定义global变量,函数体内可以使用。


Copy after login

(2)在函数体外定义global变量,函数体内不可以使用。


Copy after login

2.$GLOBALS

  在 $GLOBALS 数组中,每一个变量为一个元素,键名对应变量名,值对应变量的内容。$GLOBALS 之所以在全局范围内存在,是因为 $GLOBALS 是一个超全局变量。注意$GLOBALS 的写法,比如变量$a1,写法为$GLOBALS['a1']。

示例:先使用global定义


Copy after login

使用$GLOBALS定义全局变量


Copy after login

eg:global


function test() 
{ 
    global $a;//定义全局变量a 
    unset($a); //删除变量a
    //print $a;//会报错,因为unset已经把$a删除了。 } 
$a = 2; //定义一个变量atest(); //调用test()方法print $a; //输出a,输出的其实是$a = 2,所以结果为2.
Copy after login

eg:$GLOBALS


function test_global() 
{ 
    global $var1, $var2; 
    $var2 =& $var1; 
} 
function test_globals() 
{ 
    $GLOBALS['var3'] =& $GLOBALS['var1']; 
} 
$var1 = 5; 
$var2 = $var3 = 0; 

test_global(); 
print $var2; //输出结果为0test_globals(); 
print $var3; //输结果为5
Copy after login

The above is the detailed content of 关于PHP中的全局变量global和$GLOBALS的不同区分 - WORSHIP亚萨. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
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 [email protected]
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!