12

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!

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

3

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;
}

...
}

1 Comment

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.
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

2 Comments

And how to check if the variable presented if the value is NULL?
@Intacto You mean $var === NULL?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.