【发布时间】:2012-05-25 16:09:06
【问题描述】:
我被要求编写一个小的 PHP 脚本,该脚本从几个下拉框中获取一些 POST 输入,这些下拉框给出了一些可选择的标准,最后,吐出一个或多个包含唯一代码的字符串变量。
变量names 的形式是$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;
...
...
...
}
似乎代码正在变成箭头反模式。我想我可以使用多维数组或单个数组来做一些事情,我将值与键进行匹配。但我觉得那是在抓着稻草,一定有什么我错过了。是时候将字符串转换为具有属性的适当对象了吗?
【问题讨论】:
-
像 '$thing1Place1Type1' 这样的变量 - 这只是伪代码,还是您真的需要评估变量名?
-
任何时候你有一堆名称非常相似的变量,你很有可能需要重新评估你的设计。例如。
$thing1place1、$thing1place2等非常自然地映射到例如$things_places = array( 1 => array( 1 => 'some place', 2 => 'another place' ), 2 => ... );(或者您也可以使用显式键名,例如'places' => array( 1 => ... ))。转向更合理的数据模型,您会发现此类问题更易于管理,即使不是不存在。
标签: php nested switch-statement anti-patterns