Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
392 views
in Technique[技术] by (71.8m points)

php - what is the difference between GLOBALS and GLOBAL?

In PHP I want to know the differences between the GLOBAL and GLOBALS.

Some example:

print_r($GLOBALS);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

That are two different things related to the same: global variables.

$GLOBALS - PHP superglobal array representing the global variable table accessible as an array. Because it's a superglobal, it's available everywhere.

An associative array containing references to all variables which are currently defined in the global scope of the script. The variable names are the keys of the array.

global - Keyword to import a specific global variable into the local variable table.


Then you asked:

But why we cant access the session and cookie variables by using $GLOBALS?

That's wrong, you can access session and cookie variables by using $GLOBALS:

$GLOBALS['_SESSION']['session_variable_name']

However $_SESSION is a superglobal as well, so you don't need to use either $GLOBALS nor global to access session variables from everywhere:

$_SESSION['session_variable_name']

Same applies to $_COOKIE.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...