In previous versions of Drupal, the current user was available as the global $user variable. This approach was often unstable, and in some cases resulted in a potential security risk.
In Drupal 8, global $user has been deprecated in favor of a current_user service.
Drupal 7:
public function behave() {
global $user;
if ($user->uid == 1) {
return "Hiya, boss!";
}
else {
return "You are not the site administrator.";
}
}
Drupal 8:
public function behave() {
$account = \Drupal::currentUser();
if ($account->id() == 1) {
return "Hiya, boss!";
}
else {
return "You are not the site administrator.";
}
}
Note that in neither case is the value an actual User object. Rather, as of Drupal 8 it is a UserSession object, which duplicates some, but not all, of the information of a user. It may also represent the Anonymous User rather than a saved User entity. See https://drupal.org/node/2017231 for more information.
NOTE: The global $user variable still exists as it is necessary for certain portions of the installer and simpletest, but its use by modules is not supported and should be considered deprecated.