PHP: Where to place return 'false' value?
Is one of the following functions better than the other, in terms of where to place the 'return false' statement?
Function #1:
function equalToTwo($a, $b)
{
$c = $a + $b;
if($c == 2)
{
return true;
}
return false;
}
Function #2:
function equalToTwo($a, $b)
{
$c = $a + $b开发者_如何学Python;
if($c == 2)
{
return true;
}
else
{
return false;
}
}
Thanks!
There is no functional difference between the two; you should choose whichever one is most obvious and readable.
I would usually use an else
.
Note that your particular example should be written as
return $c == 2;
What about just:
return ($c == 2);
In this case choose whichever is more easily readable for you, since it's such a small function.
In cases where the function is much larger it's usually best to do something like this...
function do( $var=null ) {
if ( $var === null ) {
return false;
}
// many lines of code
}
In this case it would matter. Fail right away. Because it is much more readable than...
function do( $var=null ) {
if ( $var !== null ) {
//many lines of code
}
else {
return false;
}
}
There is no difference between them. In my opinion they're both equally readable, and there is no noticeable performance different either.
精彩评论