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!
Use the instanceof operator to check if an object is a Set - myObj instanceof Set . The instanceof operator returns true if the prototype property of a constructor appears in the prototype chain of the object.
The isset() function is an inbuilt function in PHP which checks whether a variable is set and is not NULL. This function also checks if a declared variable, array or array key has null value, if it does, isset() returns false, it returns true in all other possible cases.
The isset() function checks whether a variable is set, which means that it has to be declared and is not NULL. This function returns true if the variable exists and is not NULL, otherwise it returns false.
To check if list is empty in R programming, we have to evaluate the condition that the length of list is zero. Call length() function with this list passed as argument and if the return value is 0 using equal to operator.
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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With