这是我的代码:
$order_newest = $order_votes = $order_featured = $order_frequent = '';
if ( isset($_GET['o']) || isset($_COOKIE['qanda_questions_order']) ) {
// To read from the cookie
if ( !isset($_GET['o']) ) {
$_GET['o'] = $_COOKIE['qanda_questions_order'];
} else {
setcookie("qanda_questions_order", $_GET['o'], 2147483647);
}
switch ($_GET['o']) {
case 'newest':
$order_newest = 'order_active';
break;
case 'votes':
$order_votes = 'order_active';
break;
case 'featured':
$order_featured = 'order_active';
break;
case 'frequent':
$order_frequent = 'order_active';
break;
default:
$order_newest = 'order_active';
break;
}
} else {
$order_newest = 'order_active';
}
如你所见,我已经在这条线上初始化了一个超级高地:
$_GET['o'] = $_COOKIE['qanda_questions_order'];
这样做是对的吗?或者只应将supergobals用作URL (get method)中的传递参数?
我还可以更好地编写这种逻辑吗? (对我来说似乎不专业)
答案 0 :(得分:1)
意见各不相同,但在我看来,修改由PHP预先填充的超级全局是非常糟糕的做法。我总是将它们视为“只读”变量($_SESSION
除外),尽管没有什么能阻止你写它们。我个人会使用一个变量:
if (isset($_GET['o']) || isset($_COOKIE['qanda_questions_order'])) {
$order = isset($_GET['o']) ? $_GET['o'] : $_COOKIE['qanda_questions_order'];
setcookie("qanda_questions_order", $order, 2147483647);
switch ($order) {
// etc.
}
}
答案 1 :(得分:1)
我认为修改超全局没有任何问题,但您不需要这样做,也不需要创建另一个变量。
if ( isset($_GET['o']) ) {
setcookie("qanda_questions_order", $_GET['o'], 2147483647);
}
switch ($_GET['o'] ?? $_COOKIE['qanda_questions_order'] ?? '') { // ... cases