by joshstrange · 2y ago · 0 comments
Use isset if you want to see if the variable is set, you should never be casting client input unless it’s coming from query params (or form post I guess but at that point use JSON).
“empty” is a useful tool, provided you take into account things like “is this allowed to be 0/empty-string/etc”.
Lastly:
> After a lengthy debugging session, we realized that empty() was treating 0 as "empty", causing our validation to fail unexpectedly.
Lengthy? To notice an empty check failing? Look, the codebase I work on has its warts, all older codebases do, but unless you have no XDebug, forgot how to log to file or echo to the client, and/or aren’t capable of searching a codebase for the error you got and tracing it back from there then I can’t believe that would be a “Lengthy” process to track down. Even if you are returning a generic error to the client, surely you are logging the real error to a log somewhere?
we had some errors that were happening to only one client and noone could reproduce that.
I don't know enough PHP.
Does isset return true or false if I set a string variable to "" before I call isset?
Example:
$myVar = null;
var_dump(isset($myVar)); // false
$myVar = '';
var_dump(isset($myVar)); // true
$myVar = '0';
var_dump(isset($myVar)); // true
$myVar = 0;
var_dump(isset($myVar)); // true
If you have a property on a class that was never given a value it will also return `false`: class MyClass {
public $myProp;
function myFunction() {
var_dump(isset($this->myProp)); // false
}
}I think the problem is finding a short name for a little complex functionality
isset is like is_null but one thing isset can do is look at a whole chain (class props or associate array keys) and not blow up.
What I mean by that is you can do
$test = null;
isset($test->fake[‘doesNotExist’]->stilFake); // false
Whereas is_null would throw an error trying to walk a fake path. “isset” does essentially a try/catch-type thing around the check it’s doing.