...

View Full Version : more concise way of avoiding unpredefined error messages...?



cfructose
08-24-2007, 02:40 PM
This works:


if (!isset($_SESSION['logged_in']) || (isset($_SESSION['logged_in']) && $_SESSION['logged_in'] == "no")) {
show login form;
}

But it seems so verbose. Is there a simpler way I'm missing?

(BTW, I need to be able to detect the dfference between 'was logged in during this session but has now logged out' and 'hasn't ever logged in'. Hence, the need to differentiate between an undefined $_SESSION['logged_in'], and $_SESSION['logged_in'] = "no").

Thanks

Mwnciau
08-24-2007, 02:54 PM
if (empty($_SESSION['logged_in']) || $_SESSION['logged_in'] == "no") {
show login form;
}

You could do it just like that

cfructose
08-24-2007, 02:56 PM
Ah!

Thanks a lot.
:-)

aedrin
08-24-2007, 03:59 PM
It's better to use isset() (if possible, always use the more logical sounding/looking method of doing something, as it improves your code's readability).



if (!isset($_SESSION['logged_in']) || $_SESSION['logged_in'] == "no") {
show login form;
}


The reason you don't need a second isset() is that || and && are short circuited by PHP. Meaning that in an Or (||) test, if one of them is true (the first part), you don't care about the second part anymore. So if logged_in is not set as a session variable, it won't check the other part of the test. So you don't have to worry about any warnings/errors.

Mwnciau
08-24-2007, 04:19 PM
empty() is identical to isset() but also returns true if the variable has no value. (false or nothing)

aedrin
08-24-2007, 04:28 PM
Correct, but that is not the reason I gave. (And that variable should not be empty at any time, so the additional check is not useful)


always use the more logical sounding/looking method of doing something, as it improves your code's readability

What I meant by this is that someone who reads the empty() variation might not realize it is doing the same as isset().

If using one function over the other makes no functional difference, but the naming or use of that function makes it easier to read your code (as in: more like normal language), then I'd suggest using the one that reads most logical.

Clean code is an important element that few tutorials out there teach, and books don't always spend enough time on it.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum