如何知道用户是访客还是登录会员?


Answers:


57

为了使代码更健壮和更具描述性,可以使用方便的User::isAnonymous()方法,例如

if (\Drupal::currentUser()->isAnonymous()) {
  // Anonymous user...
}

2
尽可能使用如下方法:编程接口而不是实现。使用带有代码完成功能的IDE对于Drupal 8的工作是非常宝贵的。
mpdonadio

3
对于遇到此问题的任何人,请注意\ Drupal :: currentUser()-> isAuthenticated()等效于D7 user_is_logged_in()
Jaypan

我创建了一个自定义模块,但无法使用此功能。我需要在模块中添加其他内容吗?先感谢您。
SuperTony


-4

你可以使用以下代码:

global $user;
if ($user->uid == 0) {
  //user is not logged in
}else{
  //user is logged in
}

2
Drupal代码适用于Drupal 7,但不适用于Drupal 8
Dev

1
是的,请使用===进行严格比较,并在其他代码之前和之后放置空格以用于编码标准:/
klidifia
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.