Search code examples
phpsuperglobals

PHP Superglobals in another file


I want to declare a variable (php code) in file file_one and use it in file_two.

According to its documentation, superblogals can be accessed from everywhere. But not in my case maybe?? I declared $a in the first file but I am not able to use it in the second file. Although I can use it in a function inside the first file.

$GLOBALS['a']= 3;

function test() {
  echo $GLOBALS['a'];
} 

test();

This works as expected. But:

file_one:

    $GLOBALS['a']= 3;

file_two:

    echo $GLOBALS['a'];

causes a Notice: Undefined index: a

Include 'file_one.php" is not something I want to use, bebause file_one makes a lot more things.


Solution

  • Store the value of global in a session variable. It will work. Or you can define it in your head/header/function or in any common file.