I've a Drupal file (mymodule.module) which contains something like(actual code is very long):
$test =1;
//hook_user_login
function mymodule_user_login()
{
global $test;
print "$test";
}
But when this hook function "mymodule_user_login" is called by Drupal on user login -- $test's value is found to be null.
What could be the reason?
I've tried Googling but could not find useful answer.
The only way this could not work is if the file is included inside a function. E.g., your code is in foo.php
, and is executed as:
function drupal_bar() {
include 'foo.php';
}
Then $test
would not be in the global
scope, hence the function cannot get it from there either. I don't know Drupal, but it seems likely that this would be the case.
The real solution is not to use the global
scope, precisely because of this and because global state soon devolves into madness.
The localised solution for this particular case is to also write global $test
before $test = 1
to explicitly declare the variable in the global scope, wherever it may be included from later.