4

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

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

  • 一个“事物”或所有“事物”在一起
  • 一个“地方”或所有“地方”在一起
  • 一种“类型”或所有“类型”一起

如果不求助于嵌套的 switch 语句,我无法弄清楚如何选择这些代码

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

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

4

3 回答 3

4

您需要将代码重构为函数。例如:-

switch($_POST['thing'])
{
  case "thing1":
      $result = processThings($thing1);
      break;
  case "thing2":
      $result = processThings($thing2);
      break;
}

function processThings($thing)
{
    //processing code goes here
}

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

于 2012-05-25T16:18:18.457 回答
2

如果您想将它们转换为对象..您可以创建它。

  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();
    }
于 2012-05-25T16:45:01.473 回答
0

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

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

$evaluatedVariable = $$variableName;

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

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

于 2012-05-25T16:18:27.010 回答