用PHP编写Switch的更好方法?

时间:2012-09-20 23:20:59

标签: php switch-statement

我使用下面的这个例子来询问如何将数组传递给Switch,而不是像这样将它们全部列出来?

也许如果我从数据库中获取所有“页面”作为页面的数组。

我认为这种方法不是最优雅的方法。

switch($_GET['page'])
{
case 'home':
    include('home.php');
    break;
case 'oem-customers':
    include('oem-customers.php');
    break;
case 'job-shop': 
    include('job-shop.php');        
    break;
case 'anodized-magnet-coils':
    include('anodized-magnet-coils.php');
    break;
case 'design':
    include('design.php');
    break;
case 'services':
    include('services.php');
    break;
case 'black-foil':
    include('black-foil.php');
    break;  
case 'contact':
    include('contact.php');
    break;
case 'order';
    include('order.php');
    break;
default: 
    include('home.php');
}

3 个答案:

答案 0 :(得分:3)

数组示例:

$pages = array(
    'oem-customers',
    'job-shop',
    'anodized-magnet-coils',
    'design',
    'services',
    'black-foil',
    'contact',
    'order' 
);

if(in_array($_GET['page'], $pages)){
    include($_GET['page'].'.php');
}else{
    include('home.php');
}

答案 1 :(得分:3)

您可以创建映射:

$mapping = array(
   'home' => 'home',
   'oem-customers' => 'oem-customers',
   #....
);

$page = $_GET['page'];
$file = isset($mapping[$page]) ? $mapping[$page] : 'home';
include($file.'.php');

或者首先查找文件,检查文件是否存在,并在需要时使用额外的映射。注意:清理输入,用户可以在请求中发送../../etc/whatever

答案 2 :(得分:2)

好吧,你似乎在$_GET['page']和页面文件名之间有很好的匹配;一件容易的事情是:

   $toInclude = "{$_GET['page']}.php";
   include($toInclude);

当然,你要小心;有人可以通过page传递不良内容来欺骗你,例如' ../../ some_other_project / delete_all_data.php'。所以可以保留您允许的所有页面的验证列表:

   $validPages = array('order.php', 'home.php');
   if (!in_array($toInclude, $validPages))
       $toInclude = 'home.php';