The answer to "Is there a function to get the current user object that avoids accessing the global variable?" includes this:
In Drupal 8, you simply use the static method \Drupal::currentUser() to get the equivalent of Drupal 7 $GLOBALS['user']
I tried to use the following code:
$user = \Drupal::currentUser(); $name = $user->get('name')->value;
But that results in an error like so:
Fatal error: Call to undefined method Drupal\Core\Session\AccountProxy::get() in /home/remindme/uhoc.org/modules/testmodule/src/Form/FruitForm.php on line 173 (Line 173 is
$name = $user->get('name')->value;
Do I need to used some namespace or there is some other way to access the user object?