简体   繁体   中英

PHP, better to set the variable before if or use if/else?

So a simple one that I just never could find a straight answer on.

What is better (performance or otherwise):

$var = false;
If ($a == $b) {
    $var = true;
}

or

If ($a == $b) {
    $var = true;
} else {
    $var = false;
}

I've heard arguments for both ways. I find the first cleaner to ensure I have it set, and a little less code too. The pro being that you may only need to set it once without conditional. But the con being that if the argument is true, it gets set twice.

I am assuming the second way is probably best practice

I believe there is no performance difference in such cases or it's negligible. However, I think that for initialization the clearest way is to write

$var = ($a == $b);
//or
$var = ($a==$b) ? true:false;

Clarification: I don't think there is any performance gain, so that's why I think this is 100% subjective and depending on your team (like indentation, and where to put your mustaches ({) ). Its style.

That said, the first would be my option if there is a really definate default, and only in some extreme case (like "name == 'specialname') the assignment is used.

The second if for every run it is either this or else that. So it could depend on the meaning of the code in real life scope.

I my opinion the first code is better.

If you accidentally write an IF that doesn't check all cases (you forgot the final else) you will have always the the variabile with a default value setted.

I am unsure if there is an exact definite answer. However, I would answer with this - be consistent and/or follow your company's dev guidelines.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM