如何替换嵌套开关语句


How to replace nested switch statements

我被要求编写一个小的PHP脚本,该脚本从几个下拉框中获取一些POSTed输入,这些下拉框提供了一些可选的条件,最后,吐出一个或多个包含唯一代码的字符串变量。

变量名称的形式为 $thingPlaceType,并且每个都是唯一的。下拉框允许选择:

    要么是一个"事物"
  • ,要么是所有"事物"在一起
  • 要么是一个"地方"
  • ,要么是所有"地方"在一起
  • 一个"类型"
  • 或所有"类型"一起

我不知道如何在不诉诸嵌套开关语句的情况下选择这些代码

switch($_POST['thing'])
{
  case "thing1":
     switch($_POST['place'])
     {
       case "place1":
          switch($_POST['type'])
          {
            case "type1":
               $output = $thing1Place1Type1;
            case "type2":
               $output = $thing1Place1Type2;
            case "alltypes":
               $output = $thing1Place1Type1.$thing1Place1Type2.$thing1PlaceType3;
           }
        case "place2":
        ...
        case "allplaces":
        ...
      }
  case "thing2":
     switch($_POST['place'])
     {
       case "place1":
          switch($_POST['type'])
          {
            case "type1":
               $output = $thing1Place1Type1;
            ...
      ...
  ...
}

代码似乎正在变成箭头反模式。我想我可以使用多维数组做一些事情,或者可能是单个数组,我将值与键匹配。但我觉得这是在抓住稻草,一定有什么我错过了。是时候将字符串转换为具有属性的适当对象了吗?

您需要将

代码重构为函数。例如:-

switch($_POST['thing'])
{
  case "thing1":
      $result = processThings($thing1);
      break;
  case "thing2":
      $result = processThings($thing2);
      break;
}
function processThings($thing)
{
    //processing code goes here
}

我相信你明白了。如果您愿意,您可以在函数中有更多的开关块,这将避免您的反模式并使您的代码更易于理解。

如果你想把它们转换成对象......你可以创建这个。

  class Object {
        private $thing;
        private $place;
        private $type;
        public function __construct() {
            $this->thing = $_POST['thing'];
            $this->place = $_POST['place'];
            $this->type  = $_POST['type'];
            $this->processThing($this->thing, $this->place, $this->type);
        }
        public function processThing($thing = false, $place = false, $type = false) {
               //noW that you have all the properties you just need just process it
        }
    }
    if(isset($_POST['thing']) && isset($_POST['place']) && isset($_POST['type'])) {
        $object = new Object();
    }

好吧,如果你能找到一种方法来避免人们损害你的网站 - 也许通过在目标变量名称上使用前缀,那么你也许可以做到这一点:

$variableName = "A prefix_".$_POST['thing'].$_POST['type'].$_POST['place'];
$evaluatedVariable = $$variableName;

这些称为"变量变量"。 可能我会因为使用它们而感到愤怒,但如果你能负责任地使用它们,我发现它们在过去很有用。

当然,这不会直接适用于您的"所有类型"案例。 您可以使用该建议重构为函数