2010-12-01 348 views
3

我试图优化下面的PHP If/Else语句。我可以重写代码以便使用caseswitch,还是应该保留它,或者是什么?优化PHP如果/其他语句

代码:

if(empty($_GET['id'])){ 
    include('pages/home.php'); 
}elseif ($_GET['id'] === '13') { 
    include('pages/servicestatus.php'); 
}elseif(!empty($_GET['id'])){ 
    $rawdata = fetch_article($db->real_escape_string($_GET['id'])); 
    if(!$rawdata){ 
     $title = ""; 
     $meta['keywords'] = ""; 
     $meta['description'] = ""; 
    }else{ 
     $title = stripslashes($rawdata['title']); 
     $meta['keywords'] = stripslashes($rawdata['htmlkeywords']); 
     $meta['description'] = stripslashes($rawdata['htmldesc']); 
     $subs = stripslashes($rawdata['subs']); 
     $pagecontent = "<article>" . stripslashes($rawdata['content']) . "</article>"; 
    } 
    include("includes/header.php"); 
    echo $pagecontent; 
    if(!$rawdata){ 
     error_404(); 
    } 
} 

感谢

回答

2

我讨厌开关语句,但其个人偏好要诚实。至于进一步的优化,我建议看看某种形式的汇编语言。它会给你一些关于如何使条件语句更高效的一般想法。也就是说,它会给你一个不同的外观。

if(!empty($_GET['id'])) 
    { 

    if($_GET['id'] == '13') 
    { 
     include('pages/servicestatus.php'); 
    } 
    else 
    { 
     $rawdata = fetch_article($db->real_escape_string($_GET['id'])); 

     if (!$rawdata) { 

      $title = ""; 
      $meta['keywords'] = ""; 
      $meta['description'] = ""; 
     } else { 

      $title = stripslashes($rawdata['title']); 
      $meta['keywords'] = stripslashes($rawdata['htmlkeywords']); 
      $meta['description'] = stripslashes($rawdata['htmldesc']); 
      $subs = stripslashes($rawdata['subs']); 
      $pagecontent = "<article>" . stripslashes($rawdata['content']) . "</article>"; 
     } 

     include("includes/header.php"); 
     echo $pagecontent; 
     if (!$rawdata) { 

      error_404(); 
     } 
    } 
} 
else 
{ 
    include('pages/home.php'); 
} 
2

你可能想看看你的代码分解成一个MVC形式;这会让维护代码变得更容易。至少把最后一个子句放到另一个文件中,大概叫做default.phpinclude吧。另外,您可以创建一个id =>文件键/值集的数组,查找id并包含文件。

if (isset($_GET['id'])) { 
    $pages = array(
     0 => 'home.php', 
     13 => 'servicestatus.php' 
    ); 
    if (isset($pages[$_GET['id']])) { 
     include('pages/' . $pages[$_GET['id']]); 
    } else { 
     include('pages/default.php'); 
    } 
} 
+0

尽我所愿,代码是内容管理系统的一部分,大部分内容是动态的。 :( – bear 2010-12-01 20:15:52

2

好吧,我不认为这是必要切换到开关等 ,但你可以改变

} elseif (!empty($_GET['id'])) { 

只是,如果你有几个离散

}else{ 
2

switch将是适当的您正在检查的$_GET['id']的值。

一个建议我可以为可读性的原因是,

} elseif (!empty($_GET['id'])) { 

仅需要

} else { 
1

是,开关被评估一次,比if elseif高效,
是用此给定结构更容易维护

switch ($_GET['id']) 
{ 
    case 13: ... break; 
    case 0 : ... break; 
    default: ... break; 
} 
1

我不知道,如果你应该或不应该,但在这里我不会。主要的原因是,至少有一个说法,你可以省略,然后,你将有只是一个if-elseif-else语句来

if (empty($_GET['id'])) { /* code */ } 
elseif ($_GET['id'] === '13') { /* code */ } 
elseif (!empty($_GET['id'])) { /* code* } 

相同

if (empty($_GET['id'])) { /* code */ } 
elseif ($_GET['id'] === '13') { /* code */ } 
else { /* code* } 

在后挡那个声明if(!$rawdata)也是重复的。

+0

应该或不应该?你应该总是试图优化你的代码,你的先生是“臃肿软件”的主要原因之一 – 2010-12-01 20:49:48