Reputation: 6697
Here is my code:
$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';
}
As you see, I've initialized a supergobal on this line:
$_GET['o'] = $_COOKIE['qanda_questions_order'];
Is doing that a right thing? Or only should supergobals be used as passed parameters in the URL (get method) ?
Also can I write this logic more better? (seems Unprofessional to me a little bit)
Upvotes: 0
Views: 56
Reputation: 41810
I don't think there's anything wrong with modifying the superglobal, but you don't need to do so, and you don't need to create another variable either.
if ( isset($_GET['o']) ) {
setcookie("qanda_questions_order", $_GET['o'], 2147483647);
}
switch ($_GET['o'] ?? $_COOKIE['qanda_questions_order'] ?? '') { // ... cases
Upvotes: 1
Reputation: 11328
Opinions vary, but in my opinion it is really bad practice to modify superglobals that are pre-filled by PHP. I always treat them as "read-only" variables (with the exception of $_SESSION
) myself, even though there's nothing stopping you from writing to them. I would personally use a variable for this:
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.
}
}
Upvotes: 1