应该如何布尔前pressions写在PHP? [英] How should boolean expressions be written in PHP?
问题描述
应该如何以下布尔前pression可以用PHP写的:
$ foo的=;
如果(是$ var == TRUE){
$ = foo的栏;
}
或
如果(是$ var == TRUE){
$ = foo的栏;
}其他{
$ foo的=;
}
或
$ foo的=(是$ var == TRUE)? 吧:;
首先,真正
是不是一个恒定的,这是一个道理,所以请不要大写它(我知道有些标准做到这一点,但我认为它混淆的意思)......
二,你不需要多余的是$ var ==在
比较。这是完全一样的如果
真正如果($ VAR){
(对于双 ==
比较。等同比较 ===
将需要显式)。
第三,我preFER的pre-初始化。所以:
$富='';
如果($ VAR){
$ foo的='之一的地位;
}其他{
$ foo的='另一个身份;
}
如果您不需要else分支,只是将其删除。我preFER的pre-初始化,因为它迫使你初始化变量,而且prevents情况下,你忘记的一个分支进行初始化。此外,它给你一个类型提示,当你回去以后读功能...
和像一个简单的分支,使用三元语法是罚款。如果有更复杂的逻辑,我会躲得远远的,但:
$ foo的= $ VAR? '酒吧':'';
How should the following boolean expression be written in PHP:
$foo = "";
if($var==TRUE){
$foo = "bar";
}
or
if($var==TRUE){
$foo = "bar";
}else{
$foo = "";
}
or
$foo = ($var==TRUE) ? "bar": "";
First off, true
is not a constant, it's a token, so please don't uppercase it (I know some standards do that, but I think it confuses the meaning)...
Second, you don't need the redundant $var == true
comparison inside the if
. It's exactly the same as if ($var) {
(For a double ==
comparison. An identical comparison ===
would need to be explicit).
Third, I prefer the pre-initialization. So:
$foo = '';
if ($var) {
$foo = 'one status';
} else {
$foo = 'another status';
}
If you don't need the else branch, just remove it. I prefer the pre-initialization since it forces you to initialize the variable, and it prevents cases where you forget to initialize it in one of the branches. Plus, it gives you a type hint when you go back to read the function later...
And for a simple branch like that, using the ternary syntax is fine. If there's more complex logic, I'd stay away though:
$foo = $var ? 'bar' : '';
这篇关于应该如何布尔前pressions写在PHP?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!