包含带有$ _GET switch语句的文件吗? [英] Include files with $_GET switch statement?

查看:96
本文介绍了包含带有$ _GET switch语句的文件吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

伙计们!我是新手.我一整天都在想,但还是不多.

guys! I am a newbie. I think about it all day but still not much..

我有一个index.php文件,一个switch语句:

I have one index.php file, one switch statement:

    $current_page = $_GET['page'];

    switch ($current_page) {
        case ('homepage'):
            include 'contents/homepage.php';
            break;
        case ('about'):
            include 'contents/about.php';
            break;
        case ('contacts'):
            include 'contents/contacts.php';
            break;
        default:
            include 'contents/homepage.php';
    }

如果get属性是某些名称,我会包含一个文件. 如果该URL例如:myproject/index.php?page = about 包含正确的内容文件.

I include a file if the get attribute is some of the names. And if the URL is for example: myproject/index.php?page=about The proper content file is included.

但是当URL只是:myproject/index.php时 没有文件.

But when the URL is just: myproject/index.php No file is included.

我当时想添加以下内容:

I was thinkig to add something like:

    if (!isset($_GET['page'])) {
        header('Location: index.php?page=homepage');
    }

但是我认为这有点丑陋,URI不能仅是index.php.如果参数不是"page"怎么办...这又是一个问题.

But it is kind of ugly I think and the URI cannot be nver just index.php.. And what if the parameter is not "page"... It is a problem again.

您是否为此想到了一些简单易懂的解决方案.如何根据不同的页面包含适当的内容?

Do you have in mind some simple understandable solution for this. How to include the proper contents according to the different pages?

非常感谢!

推荐答案

首先,在检查是否设置了数组的键时,请使用array_key_exists.对于解析器来说,速度要快得多.

First, when checking if an array's key is set, use array_key_exists instead. It is much faster for the parser.

第二,您不应该重定向页面.而是使用默认值,如下所示:

Second, you shouldn't redirect the page. Instead, use a default value, like so:

// Set default value
$current_page = 'homepage';

// Change value if `page` is specified
if(array_key_exists('page',$_GET) {
    $current_page = $_GET['page'];
}

// Check page
switch ($current_page) {
    case 'about':
        include 'contents/about.php';
        break;
    case 'contacts':
        include 'contents/contacts.php';
        break;
    case 'homepage':
    default:
        include 'contents/homepage.php';
}

此外,如上所述,您无需为首页指定两次包含.如果没有break语句,则解析器将进入下一个case语句.如果要相同地对待多个值,则可以随后简单地指定它们.

Additionally, as I have done above, you don't need to specify the include for homepage twice. Without a break statement, the parser will go into the next case statement. If you want to treat multiple values the same, you can simply specify them subsequently.

我希望这会有所帮助!

这篇关于包含带有$ _GET switch语句的文件吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆