优化PHP代码(尝试确定最小/最大/之间的情况)

时间:2011-01-07 15:32:29

标签: php optimization switch-statement

我知道这个代码位不符合最佳编码实践,并且正在寻求改进它,任何想法?

if ($query['date_min'] != _get_date_today())
    $mode_min = true;
if ($query['date_max'] != _get_date_today())
    $mode_max = true;

if ($mode_max && $mode_min)
    $mode = "between";
elseif ($mode_max && !$mode_min)
    $mode = "max";
elseif (!$mode_max && $mode_min)
    $mode = "min";
else
    return;

if ($mode == "min" || $mode == "between") {
    $command_min = "A";
}
if ($mode == "max" || $mode == "between") {
    $command_max = "B";
}
if ($mode == "between") {
    $command = $command_min . " AND " . $command_max;
} else {
    if ($mode == "min")
        $command = $command_min;
    if ($mode == "max")
        $command = $command_max;
}

echo $command;

解决方案:

$mode_min = ($query['date_min'] != _get_date_today());
$mode_max = ($query['date_max'] != _get_date_today());

if ($mode_min){
    $command_min = "A";
}
if ($mode_max) {
    $command_max = "B";
}
if ($mode_min && $mode_max) {
    $command = $command_min . " AND " . $command_max;
} else {
    if ($mode_min)
        $command = $command_min;
    if ($mode_max)
        $command = $command_max;
}

1 个答案:

答案 0 :(得分:2)

从技术上讲,如果不满足条件,你的变量是未定义的,所以我只想使用:

$mod_min = ($query['date_min'] != _get_date_today());
$mod_max = ($query['date_max'] != _get_date_today());

除此之外,为什么要定义$mode变量,你还需要它吗?如果没有,您可以在最后一组$mod_min语句中使用$mod_maxif

例如:

if ($mode == "min" || $mode == "between")

似乎转化为:

if ($mod_min)

修改:编辑上次更新:

$command_min = "A";
$command_max = "B";

if ($mode_min && $mode_max) {
    $command = $command_min . " AND " . $command_max;
}
elseif ($mode_min){
    $command = $command_min;
}
elseif ($mode_max) {
    $command = $command_max;
} else {
    return;
}