PHP,最好在if之前设置变量,还是使用if / else? [英] PHP, better to set the variable before if or use if/else?

查看:225
本文介绍了PHP,最好在if之前设置变量,还是使用if / else?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个简单的答案我永远无法找到答案。



什么是更好的(表现或其他):

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

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

我听说过两种方式的争论。我找到了第一个清洁剂,以确保我设置它,并减少一些代码。专业人士可能只需要在没有条件的情况下设置一次。但问题是,如果参数为真,则设置两次。



我假设第二种方式可能是最佳做法


<说明:我认为这不是主观的,取决于你的团队(比如缩进,以及在哪里)把你的胡子({​​))。它的风格。



这就是说,如果有一个确定的默认值,第一个将是我的选择,并且仅在某些极端情况下(如name =='specialname')使用赋值。



第二次,如果每次运行都是这个或那个。所以它可能取决于现实范围内代码的含义。


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

解决方案

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.

这篇关于PHP,最好在if之前设置变量,还是使用if / else?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆