php很多elseif语句更好的表现

Joh*_*000 3 php

过去几周我在php写了一个网站,并且总是在我的脑海里有一个问题.在我的index.php上,我像这样路由所有模板文件

    if(isset($_GET['search'])){
        include_once 'template/template.search.php';
    }
    elseif(isset($_GET['newsletter'])){
        include_once 'template/template.newsletter.php';
    }
    elseif(isset($_GET['product'])){
        include_once 'template/template.product.php';
    }
    elseif(isset($_GET['categories'])){
        include_once 'template/template.categorie.php';
    }
    elseif(isset($_GET['about'])){
        include_once 'template/template.about.php';
    }
    elseif(isset($_GET['sitemap'])){
        include_once 'template/template.sitemap.php';
    }
    else
    {   
        include_once 'template/template.index.php';     
    }
Run Code Online (Sandbox Code Playgroud)

但对我来说它看起来不是很干净.处理这样的工作是否有更好的可能性?

我已经尝试过这样,但对我来说没有用

    $i = 0 ;
    switch($i){
    case(isset($_GET['search'])):
        include_once 'template/template.search.php';
        break;
    default:
        include_once 'template/template.index.php'; 
        break;
}
Run Code Online (Sandbox Code Playgroud)

编辑:更好的写作标题有点误导你们,所以我正在寻找最好的表现.

And*_*ong 11

这个怎么样?

$templates = array('search',
                   'newsletter',
                   'product',
                   'categories',
                   'about',
                   'sitemap',
                   'index');

foreach ($templates as $template)
{
    if (isset($_GET[$template]))
    {
        include_once "template/template.$template.php";
        break;
    }
}
Run Code Online (Sandbox Code Playgroud)

你真的应该指定一组有效的模板 - 它更安全.

我想另一种方法是搜索相反的方式:

$templates = array('search',
                   'newsletter',
                   'product',
                   'categories',
                   'about',
                   'sitemap',
                   'index');

foreach ($_GET as $key => $val)
{
    if (in_array($key, $templates))
    {
        include_once "template/template.$key.php";
        break;
    }
}
Run Code Online (Sandbox Code Playgroud)