我怎样才能更有效地做到这一点?

时间:2011-04-10 17:33:43

标签: php

switch ($_POST['stealmeth'])
{
    case "Plimus":
        if (!is_plimus_ref($_POST['stealrefid']))
        {
            $errorArr[] = "Reference ID doesn't match the payment method.";
        }
        break;
    case "LR":
        if (!is_lr_ref($_POST['stealrefid']))
        {
            $errorArr[] = "Reference ID doesn't match the payment method.";
        }
        break;
    case "PP":
        if (!is_pp_ref($_POST['stealrefid']))
        {
            $errorArr[] = "Reference ID doesn't match the payment method.";
        }
        break;
    case "AP":
        if (!is_ap_ref($_POST['stealrefid']))
        {
            $errorArr[] = "Reference ID doesn't match the payment method.";
        }
        break;
}

正如你所看到的,我只是一遍又一遍地做同样的事情。

有更清洁或更有效的方法吗?

6 个答案:

答案 0 :(得分:11)

您可以使用variable variables

switch ($_POST['stealmeth']) {
    case "Plimus":
    case "LR":
    case "PP":
    case "AP":
        $f = 'is_'.strtolower($_POST['stealmeth']).'_ref';
        if (!$f($_POST['stealrefid'])) {
            $errorArr[] = "Reference ID doesn't match the payment method.";
        }
}

你应该添加一个默认案例。

答案 1 :(得分:1)

嗯,问题不是你的开关案例,而是函数......你将不得不重写is_xx_ref函数......更好地在这里发布代码,它可能会被重写为一般函数,如下所示: / p>

if(!is_ref($ _POST ['stealmeth'],$ _POST ['stealrefid'])){     $ errorArr [] =“参考ID与付款方式不符。”; }

答案 2 :(得分:0)

您可以将所有案例合并为一个规则。

switch ($_POST['stealmeth'])
{
     case "Plimus":
     case "LR":
     case "PP":
     case "AP":
           if (!is_ap_ref($_POST['stealrefid']))
           {
                 $errorArr[] = "Reference ID doesn't match the payment method.";
            }
            break;
}

答案 3 :(得分:0)

     $match = "";
     switch ($_POST['stealmeth'])
        {
            case "Plimus":
                $match=is_plimus_ref($_POST['stealrefid']);
                break;
            case "LR":
                $match=is_lr_ref($_POST['stealrefid']);
                break;
            case "PP":
                $match=is_pp_ref($_POST['stealrefid']);
                break;
            case "AP":
                $match=is_ap_ref($_POST['stealrefid']);
                break;
        }

        if(!$match) 
        {
            $errorArr[] = "Reference ID doesn't match the payment method.";
        }

答案 4 :(得分:0)

$check_functions= array("Plimus"    =>  is_plimus_ref,
            "LR"        =>  is_lr_ref
            ...
            );


$check_function= $check_functions[$_POST['stealmeth']];         

if($check_function!=null && $check_function($_POST['stealrefid'])) 
{
    $errorArr[] = "Reference ID doesn't match the payment method.";
}

答案 5 :(得分:-1)

当然,如果仅仅是那四个值,你可以使用if语句吗?

if($_POST['stealmeth'] == "Plimus" || ... || $_POST['stealmeth'] == "AP"){
  if (!is_plimus_ref($_POST['stealrefid']))
    {
      $errorArr[] = "Reference ID doesn't match the payment method.";
    }
}