通过 PHP 代码初始化超全局是否正确?

Is initializing a superglobal by PHP codes a right thing?

这是我的代码:

    $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';
    }

如你所见,我在这一行初始化了一个 supergobal:

$_GET['o'] = $_COOKIE['qanda_questions_order'];

这样做正确吗?或者仅应将 supergobals 用作 URL (get 方法) 中的传递参数 ?

还有这个逻辑能不能写的更好一点? (我觉得有点不专业)

意见各不相同,但在我看来,修改由 PHP 预填充的超全局变量确实是一种糟糕的做法。我自己总是将它们视为 "read-only" 变量($_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.
    }
}

我认为修改superglobal没有什么问题,但你不需要这样做,你也不需要创建另一个变量。

if ( isset($_GET['o']) ) {
    setcookie("qanda_questions_order", $_GET['o'], 2147483647);
}

switch ($_GET['o'] ?? $_COOKIE['qanda_questions_order'] ?? '') { // ... cases