How to verify if object variable is set
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开发者_JAVA百科 { // 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!
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
.
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 $userid
s 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
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;
}
...
}
isset() works with objects too. In fact it will work with anything as long as:
- The variable has been declared in the current scope
- The variable value is different than NULL
精彩评论