In a PHP script, I define a global variable at the beginning of the script using $GLOBALS['someName'] = someValue
. This global variable is then used by someFunction
that is loaded later in the script using require
. If I'm correct, I should be able to set $someName = someValue
at the beginning of the script, and have $someName
available globally. But, when I do this, $someName
is not available to someFunction
. It only works when I use $GLOBALS['someName']
. Why doesn't $someName
work as a global variable when defined at the beginning of the PHP script?
Asked
Active
Viewed 794 times
2
-
1You need to tell PHP that you want to use the global variable in the function and not create a local one. Either with `global $someName;` or by using `$GLOBALS["someName"]` as you did. – Rizier123 Jun 25 '16 at 22:57
-
2*Hint*: its really bad practise to use globals – Jonathan Jun 25 '16 at 23:16
-
instead use $_SESSION or $_COOKIES..even $_SESSION is much better and safe...like $_SESSION['somename'] , it will work – Zaki Mustafa Jun 25 '16 at 23:20
-
You need to provide source code when you ask questions like this. It is far easier to help you than reading a narrative. – Jonathan Jun 25 '16 at 23:21
-
http://stackoverflow.com/questions/1557787/are-global-variables-in-php-considered-bad-practice-if-so-why – Jonathan Jun 25 '16 at 23:23
-
yeah@jonathan is right..always provide code snippet – Zaki Mustafa Jun 25 '16 at 23:23
2 Answers
2
When you define a variable outside a function, so it is global in the page but not accessible in the functions. To make a variable global and use in other functions, There are two ways:
You have to use
global
keyword. So, just writeglobal $someName
in the beginning of the function, and then, use them normally in the function.Do not redefine global variables as
global $someName
, but use them directly as$GLOBALS['someName']
.
Go to this reference for more info.

Siraj Alam
- 9,217
- 9
- 53
- 65
1
Okay let's give a proper example:
I will open up an interactive terminal in PHP to demonstrate accessing the global.
Interactive mode enabled
php > $myvar = "yves";
php > function testing() { echo $myvar; }; testing();
PHP Notice: Undefined variable: myvar in php shell code on line 1
php > function testing_with_global() { global $myvar; echo $myvar; }
php > testing_with_global();
yves
php >
Alternatively you can access the global with $GLOBALS['myvar']
.
But you really don't want to do this. See why.