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

Php 我怎样才能更有效地做到这一点?,php,Php,正如你所看到的,我只是一遍又一遍地做同样的事情 有更干净或更有效的方法吗?您可以使用: 您可能应该添加一个默认情况。如果只是这四个值,您肯定可以使用if语句吗 switch ($_POST['stealmeth']) { case "Plimus": case "LR": case "PP": case "AP": $f = 'is_'.strtolower($_POST['stealmeth']).'_ref'; if (!$f(

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

有更干净或更有效的方法吗?

您可以使用:


您可能应该添加一个默认情况。

如果只是这四个值,您肯定可以使用if语句吗

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.";
        }
}

好吧,问题不在于你的开关箱,而是功能。。。您必须重写is_xx_ref函数。。。最好在这里发布代码,它可能可以重写为一般函数,如下所示:

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

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

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

你可以用一个字符串来调用一个函数?@mcgrailm:正是变量使这成为可能。但是你也可以使用
call\u user\u func
。有趣的是,我本打算建议使用call\u user\u函数,但在我有机会之前,其他人都发布了代码。。。美好的work@Shaz,我知道它看起来很糟糕啊哈。事实上,我甚至无法解释它是否听起来不错。我们别再谈这个了。
if($_POST['stealmeth'] == "Plimus" || ... || $_POST['stealmeth'] == "AP"){
  if (!is_plimus_ref($_POST['stealrefid']))
    {
      $errorArr[] = "Reference ID doesn't match the payment method.";
    }
}
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;
}
     $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.";
        }
$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.";
}