Drupal - Is there a function to get the current user object that avoids accessing the global variable?

The function you could use is user_uid_optional_load(); without arguments, it returns the user object for the currently logged-in user. It still uses the global $user, and loads the full object from the database, including the fields associated to users, but it avoids your code accidentally change the content of the global variable $user, as it is not referenced from your code.

function user_uid_optional_load($uid = NULL) {
  if (!isset($uid)) {
    $uid = $GLOBALS['user']->uid;
  }
  return user_load($uid);
}

If you don't need the full object, then you can use the code already reported in the other answers. If you want to be sure you don't alter the global object, you can copy the global variable into a local variable, as in the following snippet.

$account = $GLOBALS['user'];
// Use $account.

In Drupal 8, you simply use the static method \Drupal::currentUser() to get the equivalent of Drupal 7 $GLOBALS['user'] and \Drupal\user\Entity\User::load(\Drupal::currentUser()->id()) to get a fully loaded object with all its field API fields. There isn't anymore the risk of overriding a global variable with all the consequences.
In the case you need to switch the current user with, for example, the anonymous user, the code you use in Drupal 8 is the following one.

$accountSwitcher = Drupal::service('account_switcher');
$accountSwitcher->switchTo(new Drupal\Core\Session\AnonymousUserSession());

// Your code here.

// Eventually, restore the user account.
$accountSwitcher->switchBack();

The $user object is declared as a global variable, so if you want to access it you need to use either:

global $user;
$account = $user;

or

$account = $GLOBALS['user'];

There doesn't actually seem to be a standard way to do this in Drupal. If you look at the node module for example, the node_access_grants() function uses this code:

if (!isset($account)) {
  $account = $GLOBALS['user'];
}

Whereas the very next function in the file, node_access_view_all_nodes(), uses this:

global $user;
if (!$account) {
  $account = $user;
}

The simple answer is that both are valid. I think the use of $GLOBALS is so that the variable named $user is not active in the current scope and therefore can't be overwritten by a careless call to, for example, $user = NULL further on in the function. I'm not 100% on that though.


It is as simple as declaring the (existing) global $user object within the scope of your function:

global $user;

Keep in mind that changes made to this object affect it globally, i.e.

global $user;
$user->uid = 1;

just gave the current user uid 1 privileges. This is why typically $user is assigned to $account so that data can be tinkered with without actually affecting the currently logged in user (unless, of course, you wanted to).

Tags:

Users