How to use current user object in Drupal 8? 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-&gt;get('name')-&gt;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-&gt;get('name')-&gt;value;


Do I need to used some namespace or there is some other way to access the user object?
Yes you need to use a name space, you can include the name space directly like this

$user = \Drupal\user\Entity\User::load(\Drupal::currentUser()-&gt;id());
$name = $user-&gt;get('name')-&gt;value;