As per my knowledge, any variable declared outside the function is treated as a 'Global Variable' in PHP.
To access such global variable inside the function there are two ways one is to declare is as global inside the function with the keyword 'global'. Another way is to access the global variable as an index of superglobal variable as $GLOBALS['global variable']
.
Both of the above mentioned ways do the same thing and both are valid.
But in following two programs this assumption seems to fail as both the programs are generating different outputs. I want to clear this doubt whether this assumption is 100% true or it works sometimes and sometimes not.
Please go through the following code snippets and their respective results :
Code Snippet 1 :
<?php
function destroy_foo() {
global $foo;
unset($foo);
}
$foo = 'bar';
destroy_foo();
echo $foo;
?>
Output of Code Snippet 1 :
bar
Code Snippet 2 :
<?php
function destroy_foo() {
unset($GLOBALS['foo']);
}
$foo = 'bar';
destroy_foo();
echo $foo;
?>
Output of Code Snippet 2 :
Notice: Undefined variable: foo in hello.php on line 9
The global keyword simply just import the variable into a function while $GLOBALS is PHP superglobal
array.
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.
Think of global
keyword as clone/copy
of the same variable while $GLOBALS
is an actual storage where Global variables resides and you can add to or remove from the storage whenever you want.
So whenever a clone/copy
of the variable is unset then It won't exists any more in that scope. e.x
<?php
function destroy_foo()
{
global $foo;
unset($foo);
echo $foo;-- Undefined variable: foo
}
$foo = 'bar';
destroy_foo();
?>
Hope it helps.