如何使这段代码更简单?

时间:2011-05-22 13:16:33

标签: php

if(condition 1){
 var=changeVar(var);
 changed=true;
}

if(condition 2){
 var=changeVar2(var);
 changed=true;
}

if(condition 3){
 var=changeVar3(var);
 changed=true;
}

我不喜欢changed=true;重复三次。

5 个答案:

答案 0 :(得分:7)

您可以保存旧的var,并进行比较吗?

oldVar = var;

//your code here.

changed = (oldVar != var);

我最初在那里==,但那么问题中的错误(或至少是不同的)解决方案是不是?

答案 1 :(得分:2)

<?php
if (condition 1) {
    var=changeVar(var);
}
if (condition 2) {
    var=changeVar2(var);
}
if (condition 3) {
    var=changeVar3(var);
}
changed=(condition 1||condition 2||condition 3||changed); // set changed value only if condition 1, condition 2 or condition 3 is true, keep old value otherwise
?>

答案 2 :(得分:1)

if (condition 1 || condition 2 || condition 3) {
    if (condition 1) {
        var = changeVar(var);
    }
    if (condition 2) {
        var = changeVar2(var);
    }
    if (condition 3) {
        var = changeVar3(var);
    }
    changed = true;
}

答案 3 :(得分:1)

$changed = true;
if ($cond1) {}
elseif ($cond2) {}
else { $changed = false; }

答案 4 :(得分:-1)

if(condition1||condition2||condition3) {
    switch(condition) {
        case 1: var = changeVar(var);
        break;
        case 2: var = changeVar2(var);
        break;
        case 3: var = changeVar3(var);
        break;
    }
    changed = true;
}