About the different distinctions between global variables global and $GLOBALS in PHP - WORSHIP Yasa

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

1.global

The function of Global is to define global variables, but this global variable does not apply to the entire website, but to the current page, including all files in include or require.

However, global variables defined within the function body can be used within the function body, while global variables defined outside the function body cannot be used within the function body. See the example below for details.

(1) Define global variables within the function body, which can be used within the function body.


Copy after login

(2) Define global variables outside the function body and cannot use them inside the function body.


Copy after login

2.$GLOBALS

In the $GLOBALS array, each variable is an element, the key name corresponds to the variable name, and the value corresponds to the variable's content . $GLOBALS exists in the global scope because $GLOBALS is a superglobal variable. Pay attention to the writing method of $GLOBALS. For example, the variable $a1 is written as $GLOBALS['a1'].

Example: First use global definition


Copy after login

Use $GLOBALS to define global variables


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 About the different distinctions between global variables global and $GLOBALS in PHP - WORSHIP Yasa. 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 admin@php.cn
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!