Forum Moderators: coopster
function foo($temp)
{
if ($temp >= 0)
return true;
else
return false;
}
Nothing really wrong with that only I've been told to do it like this:
function foo($temp)
{
$status = false;
if ($temp >= 0)
$status = true;
return $status;
}
Is there really any significant difference between the two? Any security risks?
--Nick
Not much of a difference at all. The first one, in my opinion, is much more readable and the way I would have done it. The second way, while it still does the same thing, makes it a little less obvious what it will return. Both are acceptable.
, which kinda makes the question moot. ;)function foo($temp) {
return $temp >= 0;
}
Generally, advice to write code that second way comes from people taking structured programming too far. Going through awful contortions to ensure a function only has one exit point is nuts when multiple exit points make more sense.
For instance, I'd much prefer
overfunction bar($quux) {
if (some_condition($quux)) return false;
// do other stuff...
return true;
}
Partially because the first is shorter, but also because it fits how I think about the problem better: "If $quux meets some condition bail out, otherwise do some actual work." versus "Uh, do some stuff, or do some other stuff, then maybe return something.".function bar($quux) {
if (some_condition($quux)) {
$ret = false;
} else {
// do other stuff...
$ret = true;
}
return $ret;
}