【问题标题】:If or Switch for getting parameter PHP [closed]If 或 Switch 获取参数 PHP [关闭]
【发布时间】:2012-11-30 02:27:50
【问题描述】:

我有很多php 文件。

访问每个php我正在使用参数。

例如:index.php?route=changepasswordindex.php?route=aboutus

我有一个route.php 将参数链接到正确的文件

更好用

If-Else statement

$route = $_GET['route'];
if ($route==changepassword) {
   //statement
} else if ($route==aboutus) {
   //statement
}

使用switch-case

$route = $_GET['route'];
switch ($route) {
case "changepassword" :
   //statement
   break;
case "aboutus" :
   //statement
   break;
}

这只是2个文件,我有10+个文件,用什么比较好?

【问题讨论】:

  • 没有比这更好的了。只有 Zuul。
  • 切换 IMO。更易于阅读、编写和维护。
  • "if" versus "switch"的可能重复

标签: php


【解决方案1】:

您应该尽可能使用数组映射:

$map = array(
    "changepassword" => "includes/changepw.php",
    "aboutus" => "templ/aboutus.php",
);

在那种简单的情况下(您没有详细说明您的//statements),您可以将它们用作:

incude( $map[$_GET["route"]] );

通常您可以将它们映射到类或回调或匿名函数上。

但最后,地图更简洁,更易于维护。

【讨论】:

    【解决方案2】:

    对于这些情况,如果使用任一解决方案都可以获得任何性能,请在性能之前先确保代码清晰。

    我肯定会选择switch-case

    看到这个other thread 有类似的答案。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-04-26
      • 1970-01-01
      • 2016-07-28
      • 2018-12-19
      • 2014-12-15
      • 1970-01-01
      • 1970-01-01
      • 2020-12-31
      相关资源
      最近更新 更多