Would appreciate it, if anyone can let me know how we can set the global $user
variable, so that we don't have to keep re-declaring it in each function, to access its contents. How can we declare it so that all the functions in a module can use it?
3 Answers
The type of global you're looking for (available always, in every scope) is called a superglobal in PHP. You cannot declare new superglobals, but you can access all globals directly because they are part of the $GLOBAL
superglobal. In other words, you can use $GLOBALS['user']
to access the $user global directly.
See also create superglobal variables in php? for more info and alternative methods.

- 1
- 1

- 5,592
- 4
- 22
- 32
-
Thanks so much. So now, I can just do $GLOBALS['user']->uid everytime I need to get the userid of the current user. – SN_26 Mar 19 '12 at 05:53
You can't...that's how globals work in PHP. If you want to import the global variable into your local function then you have to use the global
keyword, there's no way round it. This is a 'feature' of the PHP language, it has nothing to do with Drupal.
An alternative method might be to implement a helper function:
function get_current_user() {
global $user;
return $user;
}
And call it like this:
$user = &get_current_user();

- 36,918
- 8
- 87
- 113
In your function if you want to use the $user variable, you just required to use/instantiate 'global' keyword before $user it. So that you can access all the data for that current user of the website.
For example
function myGenericFunc(){
global $user;
$user_id = $user->uid;
}
Note that you cannot redeclare it.
I hope it helps.

- 1,172
- 12
- 18