11

I have a User class which is created when a user logs in

$user = new User($userId);

Now to check if a user is logged in, I tried doing

if (isset($user)) {   // user is logged in

} else {   // user is not logged in

}

However, isset() doesn't appear to work for objects? And I've also tried is_object(). Please advise! Hopefully there is a way to do this elegantly, perhaps

if ($user->isLoggedIn()) {

}

Thanks for your time!

axsuul
  • 7,370
  • 9
  • 54
  • 71

4 Answers4

12

isset() should work, object or not. You can also use

if ((isset($user)) and ($user instanceof User))

to check whether it is set and whether it is an object of the class User.

Pekka
  • 442,112
  • 142
  • 972
  • 1,088
4

The problem is that

new User($userid);

will always give you a User object, even though it's constructor, which probably looks up $userid in the database, may conclude that the object doesn't exist. You can throw an exception in the constructor for invalid $userids and use a try/catch construct instead of your isset() test, or set a User->valid property in the constructor of users that do exist and check for that in your test.

See also this question for some more ideas: PHP constructor to return a NULL

Community
  • 1
  • 1
Wim
  • 11,091
  • 41
  • 58
2

If you edit your User class you can use $user->isLoggedIn()

class User {

private $logged_in = false;

...

public function login($uid) {
  ... login code
  $this->logged_in = true;
}

public function isLoggedIn() {
  return $this->logged_in;
}

...
}
thetaiko
  • 7,816
  • 2
  • 33
  • 49
  • This is the correct answer. If you have a user and want to check if he is logged in, it's a really bad idea to use `isset($user)` to determine if the user is logged in. – MarthyM Aug 15 '17 at 09:33
1

isset() works with objects too. In fact it will work with anything as long as:

  1. The variable has been declared in the current scope
  2. The variable value is different than NULL
AlexV
  • 22,658
  • 18
  • 85
  • 122