2

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?

2 Answers2

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:

  1. You have to use global keyword. So, just write global $someName in the beginning of the function, and then, use them normally in the function.

  2. Do not redefine global variables as global $someName, but use them directly as $GLOBALS['someName'].

Go to this reference for more info.

Siraj Alam
  • 5,569
  • 5
  • 39
  • 55
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.

Community
  • 1
  • 1
Jonathan
  • 8,402
  • 8
  • 49
  • 64