Implicit Evaluation with PHP

9 February 2007

The Implicit Isset

I once wrote about the differences between array_key_exists and isset. In some instances, neither is neccessary.

In most cases, trying to access a variable which does not exist will raise a NOTICE error. The purpose of isset is to determine that, in order to avoid that error. If you do not care, or set the error reporting level high enough, they will be suppressed.

Consider checking for a permission token. You can write something like if ($male) ... instead of if (isset ($male)) ... .

The implicit isset is not identical to the real isset. The real isset will return true for 0 and string(0) "" values, and only false for null. The implicit isset will return false for all three cases.

Despite their lack of parity, there are still times when the implicit isset will suit you better than the explicit one. Consider a function with optional arguments:
function arithmetic ($number, $number2, $operation = "+") {
if (!$operation) { // operation will almost always be set, so isset doesn't tell us anything we can't already assume
$operation = "+";
}
}

Most situations leave you knowing whether a variable exists or not, so neither isset or implicit issets are necessary. But in a certain layer of abstraction, far removed from reality, being able to choose the best-suited method of variable detection can make the difference between good and confusing code.

No Comments currently posted.

Post a comment on this entry: