What is the difference between GLOBALS and GLOBAL?

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

Example:

print_r($GLOBALS); 
+6
source share
4 answers

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

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

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

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


Then you asked:

But why can't we access session and cookie variables with $GLOBALS ?

Wrong, you can access session and cookie variables with $GLOBALS :

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

However, $_SESSION also superglobal, so you do not need to use $GLOBALS and global to access session variables:

 $_SESSION['session_variable_name'] 

The same goes for $_COOKIE .

+13
source

$ GLOBALS is an array, and global is a keyword for declaring or using global variables

+2
source

These are two different things.

global - keyword , which reports that this variable is global. For instance. if you are going to access a variable inside a function defined outside, you will need to use the global keyword to make it available in the function.

$GLOBALS is a superglobal array . Superglobal simply means that it is available in all areas of the script without using a global keyword.

+2
source

$ GLOBALS: an associative array containing references to all the variables that are currently defined in the global scope of the script. variable names are array keys

GLOBAL / global is the keyword for setting the global variable.

References:

http://php.net/GLOBALS

http://php.net/global

+1
source

Source: https://habr.com/ru/post/900925/


All Articles