Where to return false in a PHP function?
Does this
function doThings(){
if($oh){
return $oh;
}
return false;
}
equal this
function doThings(){
if($oh){
return $oh;
}else{
return false;
}
}
Th开发者_JS百科ank you!
Yes, both do the same. Personally, I prefer to exit a function at the same place. e.g.
function doThings(){
$flag = false;
if($oh){
$flag = $oh;
}
return $flag;
}
In the scenario you outlined above, Yes. Either should work fine. I prefer the first method, less typing and all.
Yes, those functions are exactly equivalent in behaviour.
Yes.
Also they more or less equal to:
function doThings(){
return $oh;
}
This is not strictly true since PHP has other "falsey" values than false but if you want to return either $oh
or an falsey value then this will work fine.
Another way to write an equivalent function would be:
function doThings(){
return $oh ? $oh : false;
}
I'd write it like this:
function doThings() {
return $oh ?: false;
}
Or with earlier versions of PHP:
function doThings() {
return $oh ? $oh : false;
}
Or, depending on the function:
function doThings() {
$oh = null; // set to some default;
// do stuff
return $oh;
}
To answer this question we must first question who we are as individuals and as a people... just kidding, for all intensive purposes they're the same.
Yes they are the same.
Quicktip:
I prefer the following:
function do() {
if (!$oh) {
return false;
}
return $oh;
}
This way you do not have the extra bracets as in your second example. But you always know where your value is returned (at the end of the function). This makes it quicker to locate and browse functions.
Mo:
As already stated, the two functions do exactly the same. You might also want to try doing something like this ( there cases where this might be beneficial )
function doSomething() {
$return_value = false;
if($oh) {
$return_value = true;
}
return $return_value;
}
This doesnt do anything special, it's just a reorganisation.
Both do the same. Once the return statement is encountered, the control is passed back to the code which calls this function.
First one is preferred over the second one, because of less code.
- both having same behavior.
- you can place depends on your scenario.
Note that since return is a language construct and not a function, the parentheses surrounding its arguments are not required. It is common to leave them out, and you actually should do so as PHP has less work to do in this case.
精彩评论