应该如何布尔前pressions写在PHP? [英] How should boolean expressions be written in PHP?

查看:109
本文介绍了应该如何布尔前pressions写在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屋!

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