In PHP I want to know the differences between the GLOBAL and GLOBALS.
Some example:
print_r($GLOBALS);
In PHP I want to know the differences between the GLOBAL and GLOBALS.
Some example:
print_r($GLOBALS);
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
.
They are two different things.
global
is a keyword which tells that the variable is from a global scope. E.g. if you're about to access a variable inside a function that's defined outside you'll need to use the global keyword to make it accessible in the function.
$GLOBALS
is a superglobal
array. Superglobal simply means that it is available in all scopes throughout a script without the need of using the global keyword.
$GLOBALS is an array and global is a keyword to declare or use global variables
I think your confusion in in between $GLOBAL and $GLOBALS.
$GLOBALS is a superglobal array that it is available in all scopes throughout a script without the need of using the global keyword.
You are trying to access the session and cookie variables by using $GLOBAL and that's wrong. Please use $GLOBALS instead. $GLOBAL is nothing.
But global is a keyword which tells that the variable is from a global scope.
$GLOBALS : 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/global is a keyword for setting a variable global.
References :