Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to verify if object variable is set

Tags:

oop

php

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!

like image 959
axsuul Avatar asked Feb 16 '10 19:02

axsuul


People also ask

How do you know if an object is set?

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.

How check object is set or not in PHP?

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.

How to check variable exists in php?

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.

How do I check if a variable is empty in R?

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.


2 Answers

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.

like image 156
Pekka Avatar answered Oct 05 '22 04:10

Pekka


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

like image 41
Wim Avatar answered Oct 05 '22 03:10

Wim