tags:

views:

53

answers:

4

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!

+1  A: 

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
A: 

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
+2  A: 

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: http://stackoverflow.com/questions/2214724/php-constructor-to-return-a-null/2214769

Wim
A: 

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