Drupal 7 global user variable

Would be grateful if someone can tell me how we can set the variable global $user

so that we don't have to re-declare it in every function to access its contents. How can we declare it so that all functions in the module can use it?


source to share

3 answers

The type of global search (always available in every area) is called superglobal in PHP. You cannot declare new superglobals, but you can access all globals directly because they are part of the superglobal $GLOBAL

. In other words, you can use $GLOBALS['user']

$ user global to directly access.

See also creating superglobals in php? for more information and alternative methods.



You can't ... the way globals work in PHP. If you want to import a global variable into your local function you need to use a keyword global

, there is no way to round it. This is a "feature" of PHP, it has nothing to do with Drupal.

An alternative method could be to implement a helper function:

function get_current_user() {
  global $user;
  return $user;


And call it like this:

$user = &get_current_user();




In your function, if you want to use the $ user variable, you just need to use / instantiate "global" before $ user it. So that you can access all data for this current user of the website.

for example

    function myGenericFunc(){
      global $user;
      $user_id = $user->uid;


Please note that you cannot update it.

Hope this helps.



All Articles