Wednesday, November 20, 2013

All about $GLOBALS in PHP

PHP Superglobals or Auto-globals

In PHP there are certain predefined variables and are called superglobals or Auto-globals. Those variables are accessible throughout the program irrespective of their scope. One such is a variable named $GLOBALS.

$GLOBALS

PHP stores all the global variables (variables within global scope of the script) currently available in the script, in an associative array called $GLOBALS[index]. "index" refers to the name of the individual global variables.
 
Example:

global $myVar = 3;

global $a = 20;


"myVar" is a global variable and holds the value 3.

"a" is a global variable and holds the value 3.

implies

$GLOBALS['myVar'] = 3;

$GLOBALS['a'] = 20;


The example given below explains the $GLOBALS array.

<?php
$x = "save";

function toclose()
{
$y = "close";
}
?>

Here, $x will be stored in the $GLOBALS array (as x is declared outside the function) and $y wont be stored in the $GLOBALS array (as y is declared inside the function).

Generally a global variable has scope only outside the functions. Since $GLOBALS[] is a superglobal, this can be used to access the global variables even within the functions. Here is an example to portrait this scenario..

Code:

<?php
$myVar = 10;

function testglobals()
{
 $GLOBALS['myVar'] = 20;
}

testglobals();
echo $myVar;
?>

Result:

20

Note: From the above exemplar, we can note that, with the help of superglobal $GLOBALS, it is possible to access or modify any global variable inside any space of the program.

Some of the other PHP Superglobals are

$GLOBALS, $_SERVER, $_REQUEST, $_POST, $_GET,
$_FILES, $_ENV, $_COOKIE, $_SESSION.

These can be discussed in future posts.

No comments:

Post a Comment