简体   繁体   English

PHP if else - 正确使用“else”

[英]PHP if else - proper use of “else”

A professor told me long ago to use else when "chaining" multiple conditions in a series (I was still learning). 很久以前,一位教授告诉我,在一系列“链接”多个条件时我会使用else (我还在学习)。 Now that I've been tinkering with several frameworks and CMS years later, I find it quite amusing that what I was taught to do isn't necessarily so. 既然我几年后一直在修改几个框架和CMS,我发现我教的内容并不一定如此,这很有趣。

I was taught to use else in between a series of conditions: 我被教导在一系列条件之间使用else

function double(param){
    if(param==1){
        return param+=1;
    }
    else 
    if(param==2){
        return param+=2;
    }
    else{
        return false;
    }
}

Nowadays, I seem to see this, which I was warned long ago NOT to do: 如今,我似乎看到了这一点,我很久以前就被警告不要这样做:

function double(param){
    if(param==1){
        return param+=1;
    }
    if(param==2){
        return param+=2;
    }
    return false;
}

This sample code might not work, but the idea is there: Is it necessary to use else in between every condition? 这个示例代码可能不起作用,但想法是: 是否有必要在每个条件之间使用else If so (or not so), what should I look out for when using either way? 如果是这样(或不是这样),在使用任何一种方式时我应该注意什么? There must be something that caused my professor to tell me such thing. 一定有什么东西导致我的教授告诉我这样的事情。

Using else or not using it mean two different things. 使用else或不使用它的意思是两个不同的东西。

When you wish to test a series of conditions where at most one may be true, use else or else if . 如果您希望测试一系列条件,其中最多可能是一个,则使用else或者else if When one condition evaluates true, the code in the block is executed and then the entire if-else construct is exited. 当一个条件的计算结果为true时,将执行块中的代码,然后退出整个if-else结构。

When more than one condition may be true, using else will preclude other conditions from evaluating to true, and so it would be wrong to use an else in this situation. 当多个条件可能为真时,使用else阻止其他条件评估为true,因此在这种情况下使用else是错误的。

Edit: I now see you are referring to the specific case where each clause contains a return statement. 编辑:我现在看到你指的是每个子句包含一个return语句的特定情况。 In this case it is probably better to use an else or elseif to make it clear that the if-else construct behaves in the first manner - ie. 在这种情况下,最好使用elseelseif来明确if-else构造以第一种方式运行 - 即。 at most one condition may execute. 最多可以执行一个条件。

It is not necessary to use else, as the control flow returns from the function immediately at the point of the return keyword. 没有必要使用else,因为控制流立即在return关键字点返回函数。

Further, I find using else when there is a return unnecessarily confusing, and so would prefer alternative 2 in all cases. 此外,当发现不必要的回报时,我发现使用了else,因此在所有情况下都更喜欢替代2。

It's really just a matter of opinion. 这真的只是一个意见问题。

It's not necessary to use else in a case such as this, however your professor may have been describing a different case, or perhaps he was simply having you do it for emphasized/forced clarity. 在这样的情况下没有必要使用else ,但是你的教授可能已经描述了一个不同的情况,或者他只是让你为了强调/强制清晰而做。

First of all, it's my opinion that returning different data types from the same function is generally bad style, but having said that, take your example: 首先,我认为从同一个函数返回不同的数据类型通常是糟糕的风格,但话说回来,举个例子:

function double($param) {
    if ($param == 1) {
        return $param + 1;
    } else if ($param == 2) {
        return $param + 1;
    } else {
        return false;
    }
}

Now imagine a similar example, except it doesn't return each time: 现在想象一个类似的例子,除了每次都不返回:

function double($param) {
    $returnMe = 0;

    if ($param == 1) {
        $returnMe = $param + 1
    } else if ($param == 2) {
        $returnMe = $param + 2;
    } else {
        $returnMe = false;
    }

    return $returnMe;
}

This may seem trivial (and in the examples provided it largely is), you can see that the else really does make a difference. 这似乎微不足道(并在提供它在很大程度上就是例子),你可以看到其他人确实有所作为。

In forcing everything to have an else like he did, he was probably just trying to provide some consistency in style (which I'd argue is good for newcomers). 在强迫一切都像他一样有其他东西时,他可能只是想提供一些风格的一致性(我认为这对新手来说是好的)。

Of course, you are right, in the case you presented, having the else was unnecessary. 当然,你是对的,在你提出的情况下,别的是不必要的。 Whether or not it's bad or good is really just a matter of opinion. 无论是坏还是坏都只是一个意见问题。

Scenario 1 场景1

if ($one) {
    doA();
}
if ($two) { // ALWAYS check this block - it is not attached to anything
    doB();
}

Truth table:

            | $one True | $one False 
------------+-----------+------------
$two True   | A and B   | B only   
$two False  | A only    | none

Scenario 2 情景2

if ($one) {
    doA();
}
else if ($two) {  // ONLY check this block if $one is false!
    doB();
}

Truth table:

            | $one True | $one False 
------------+-----------+------------
$two True   | A only    | B only   
$two False  | A only    | none

As you can see in the truth tables, the two scenarios are not the same. 正如您在真值表中看到的那样,这两种情况并不相同。 So, whether to use if..else or if..if is not just a matter of semantics or taste, it has an actual functional difference. 因此,无论是使用if..else还是if..if不仅仅是语义或品味问题,它还具有实际的功能差异。

In the case of returns inside of an if , it will exit the function entirely and therefore it is a special case where the result is the same as an else-if . if内部返回的情况下,它将完全退出函数,因此它是一个特殊情况,其结果else-if相同。

I think it's a good practice, becouse the flow would follow down if you forget the return clause (leading to hard-to-find bugs) 我认为这是一个很好的做法,因为如果你忘记了return条款(导致难以发现的错误),流程将会跟进

Anyway, the else clause may be too verbose in some situations, so you can use elseif : 无论如何,else子句在某些情况下可能过于冗长,所以你可以使用elseif

<?php
if ($a > $b) {
    return "a is bigger than b";
} elseif ($a == $b) {
    return "a is equal to b";
} else {
    return "a is smaller than b";
}
?>

Yes . 是的 Why? 为什么? Because these conditions are based on the same variable and only one can be met. 因为这些条件基于相同的变量,只能满足一个。 For this reason, if you use elseif (PHP) or else if (JavaScript), you will improve code visibility and possibly avoid some future errors. 因此,如果您使用elseif (PHP)或else if (JavaScript),您将提高代码可见性并可能避免将来出现一些错误。

Your code in PHP 你的PHP代码

Your code in PHP would look like this: PHP中的代码如下所示:

function double($param){
    if($param==1){
        return $param+=1;
    }
    elseif($param==2){
        return $param+=2;
    }
    else{
        return false;
    }
}

or, using switch counterpart: 或者,使用switch对应方:

function double($param){
    switch ($param) {
        case 1:
            return $param+=1;
        case 2:
            return $param+=2;
        default:
            return false;
    }
}

Your code in JavaScript 您在JavaScript中的代码

In JavaScript it would look like this: 在JavaScript中它看起来像这样:

function double($param){
    if($param==1){
        return $param+=1;
    }
    else if($param==2){
        return $param+=2;
    }
    else{
        return false;
    }
}

it really depends on the flow of your codes... sometimes you need to use separate if(s), and sometimes you need to use if(s) and else(s)... but for the sake of the example you added. 它实际上取决于代码的流程...有时您需要使用单独的if(s),有时您需要使用if(s)和else(s)...但是为了您添加的示例。 personally, I'd select the first one you wrote because its more efficient and easier to read and understand. 就个人而言,我会选择您编写的第一个,因为它更有效,更易于阅读和理解。 perhaps there are other factors and points but that's how I see it and that's why I chosen the first one.. 也许还有其他因素和要点,但这就是我看到它的原因,这也是我选择第一个因素的原因。

one more thing to add.. is that if you use the second one the compiler will always execute the second "if", if the $param was containing a different value other than "1" or "2". 还有一件事要添加..如果使用第二个,编译器将始终执行第二个“if”,如果$ param包含除“1”或“2”之外的其他值。

You may fancy this scenario I spotted not too long ago on Apple's website 您可能想象我不久前在Apple的网站上发现的这种情况

switch(true) {
    case foo == bar:
        break;
    case foo > 5:
        break;
    case foo > 10:
    case bar > 5:
        break;
}

You get the idea. 你明白了。 I believe all compilers break this down to if/else code, but I like the flexibility of controlling where the break statements are. 我相信所有编译器都会将其分解为if / else代码,但我喜欢控制break语句的灵活性

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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