I see that some developers reset the $user object in a manner similar to the following:

function my_example_callback($args) {
  global $user;
  $account = $user;
  $user = user_load(1); // Bypass access checks with User 1.
  $data = views_embed_view('my_view', 'page', $args);

  // Do things..

  // Reset the $user to the original value.
  $user = $account;

  return $data;

My question, is this really necessary? If so in what situations?

1 Answer 1


It depends..

Since you load the user object from the global scope, everything you change on it will affect other functions further down the line.

If you make alterations to the user object that only apply to your module, you might want to reset those changes so other modules won't be able to see the alterations you made. Think about adding something like adding a security key, then run it through some of your functions. You don't want other modules and functions to see the key, so you want to remove it from the user object after your functions are done with it.

For only loading the user and reading it, I'd say it doesn't make sense to reset the variable.


As for your example, to bypass the access check the global user object (current logged in user) is swapped with the object of user 1. In this case it is very important to switch back, otherwise all other functions will see you as user 1 rather than your own account!

See https://www.drupal.org/node/218104 for documentation on impersonating other users.

  • Exactly what I thought. I access global $user only to read values from this object, never to alter it.
    – W.M.
    Apr 13, 2016 at 11:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.