伙计们!我是新手.我整天想着它,但仍然没有多少..
我有一个index.php文件,一个switch语句:
$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
包含适当的内容文件.
但是当URL只是:myproject / index.php
没有包含文件.
我想想要添加如下内容:
if (!isset($_GET['page'])) {
header('Location: index.php?page=homepage');
}
但是我觉得它有点丑陋,URI不能只是index.php ..如果参数不是“页面”怎么办……这又是一个问题.
您是否考虑过一些简单易懂的解决方案.如何根据不同的页面包含适当的内容?
非常感谢你!
解决方法:
首先,在检查是否设置了数组的键时,请使用array_key_exists.解析器要快得多.
其次,您不应该重定向页面.相反,使用默认值,如下所示:
// 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语句.如果要将多个值视为相同,则可以随后简单地指定它们.
我希望这有帮助!
标签:php,switch-statement
来源: https://codeday.me/bug/20191006/1858705.html