Today while playing around PHP and stuff I have been thinking of patterns of handling optionally existing variables.
The 2 most commonly used ones are:
if (isset($var) && $var != null) doSomething($var);
if (isset($var) && $var != 0) doSomething($var);
if (isset($var) && ($var != '') doSomething($var);
if (!isset($var)) $var = something();
However my experience points me that in the majority of the cases it’s enough to check the boolean value of the variable to proceed:
if ($var) doSomething($var);
if (!$var) $var = something();
Which reads very kosher. But then we have a problem of getting notice that the variable is undefined, which is not kosher.
So the way kosherize the snippet is to enforce variable definition before usage. Meaning we would like to either use its value if it’s defined, or to initialize it with
null. But of course I don’t like to use
isset() for that. So what to do? I found an answer!
$var = &$var;
As you can see in this way you declare further usage of the variable. If the variable exists – it does nothing. If it’s not it is silently initialized with
null. No notices are yielded. Also it’s better than
if(isset()) combination because of readability – the only alphanumeric tokens on the line are variable names.
Isn’t it nice?