[英]PHP - Why is “Index.php?action=” not recognized as “Index.php?”
所有,
我正在用PHP構建一個前端控制器。 在其中,我說:
if (isset($_GET['action'])){
$action=$_GET['action'];
} else {
$action='';
}
我使用switch語句來控制根據$action
的值調用哪個控制器:
switch ($action){
case '':
require_once('Controller_Welcome.php');
$command=new controller_Welcome();
break;
case 'logon':
require_once('Controller_Logon.php');
$command=new controller_Logon();
break;
default:
require_once('Controller_Unknown.php');
$command=new controller_Unknown();
break;
}
$command->execute();
這很好用。 當我啟動應用程序時,URL是http://.../Index.php?
並調用Controller_Welcome.php
。 如果我單擊登錄菜單項,我會得到http://.../Index.php?action=logon
,並調用Controller_Logon.php
。 如果我手動編輯URL以將...?action=...
為某個未知值,我會得到Controller_Unknown.php
,這是我的錯誤頁面。 一切都很好。
我不明白的是,如果我手動更改URL以顯示http://.../Index.php?action=
,我會得到錯誤頁面而不是歡迎頁面。 為什么php沒有將一個url結尾與...?action=
與switch case $action='';
?
(當發生這種情況時,沒有合乎邏輯的用戶案例,但我仍然不理解......)
謝謝,
JDelage
PS:Var_dumping $action
返回string(0) ""
。
只是一個可能有助於提高可讀性和進一步開發工作的說明。 看起來你的命名約定可能允許更多的“ 魔術 ”,讓位於一種約定優於配置,並避免代碼重復:
define('PATH_CONTROLLERS', 'path/to/controllers/');
$action = !empty($_GET['action'])
? $_GET['action']
: 'default';
switch($action){
case 'default':
case 'welcome':
case 'authenticate':
$controller_name = "controller_{$action}";
break;
default:
$controller_name = 'controller_404';
break;
}
require PATH_CONTROLLERS . "{$controller_name}.php";
$controller = new $controller_name();
$controller->execute();
鑒於:
// index.php
$action: 'default'
$controller_name: 'controller_default'
require(): 'path/to/controllers/controller_default.php'
// index.php?action=authenticate
$action: 'authenticate'
$controller_name: 'controller_authenticate'
require(): 'path/to/controllers/controller_authenticate.php'
// index.php?action=foobar
$action: 'foobar'
$controller_name: 'controller_404'
require(): 'path/to/controllers/controller_404.php'
當你設置?action=
,你會得到$_GET['action']
的null
返回值。 因此,在您的方案中,switch語句將使用默認情況。 像所有人說的那樣,你總是可以使用var_dump來查看返回值。
我認為行動不是你想象的那樣。 這對我來說是預期的。
for url ending in 'action=' blank is echoed
for url ending in 'action=anything' anything is echoed
var_dump($_GET);
$action = $_GET['action'];
switch ($action){
case '':
echo "blank";
break;
default:
echo $action;
break;
}
您描述的行為無法再現。 我使用了以下內容,結果沒有證明你所描述的內容:
<pre>
<?php
if (isset($_GET['action'])){
$action=$_GET['action'];
} else {
$action='';
}
var_dump($action);
echo "\n";
var_dump($_GET);
echo "\n";
switch ($action){
case '':
die('empty action</pre>');
case 'logon':
die('logon action</pre>');
default:
die('unknown action</pre>');
}
?>
呼叫:
http://host.com/test.php?action=
結果:
string(0) ""
array(1) {
["action"]=>
string(0) ""
}
empty action
你的其他代碼有一些東西。
這個工作正常,並拋出Controller_Welcome空行動
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.