使用动态变量访问 $_SESSION / $_GET / ...

Accessing $_SESSION / $_GET / ... with dynamic variable

我有一个 class 负责处理所有与用户相关的数据。 在我的一种方法中,我想访问 $_SESSION / $_GET$_POST、任何 $_...

通过如下动态变量(在 _unset 方法中):

class Userdata
{
    ...
    const knownSources = ['post', 'get', 'cookie', 'session', 'files'];
    private $post = [];
    private $get = [];
    private $cookie = [];
    private $session = [];
    private $files = [];

    ...
    private function __construct()
    {
        $this->post = $this->secureVars($_POST);
        $this->get = $this->secureVars($_GET);
        $this->cookie = $this->secureVars($_COOKIE);
        ...
    }
    public static function getInstance(){...}
    public static function secureVars($inputVar, $asObject = true, $acceptHTML = false){...}

    public static function _unset($dataSource, $key)
    {
        $self = self::getInstance();

        if (in_array(strtolower($dataSource), self::knownSources))
        {
            // Here I want to unset the variable in $_SESSION[$key] for instance, but 'SESSION' can be whichever of knownSources array. 
            print_r([
                ${'_SESSION'},
                ${'_' . 'SESSION'},
                ${'_' . strtoupper($dataSource)}
            ]);
            ...
        }
    }
}

知道为什么 ${'_SESSION'} 有效但 ${'_' . 'SESSION'} 无效吗? 以及如何实现我的目标:${'_' . strtoupper($dataSource)}?

感谢您的帮助!

[编辑] 在提出建议之后,我得出了这个结论:

switch($dataSource)
{
    case 'session':
        $target = $_SESSION;
        break;
    case 'post':
        $target = $_POST;
        break;
    case 'get':
        $target = $_GET;
        break;
    case 'cookie':
        $target = $_COOKIE;
        break;
    case 'files':
        $target = $_FILES;
        break;
}
unset($self->$dataSource->$key);
unset($target[$key]);

[编辑] 在意识到它仍然行不通之后,我 - 遗憾地 - 选择:

    switch($dataSource)
    {
        case 'session':
            unset($_SESSION[$key]);
            break;
        case 'post':
            unset($_POST[$key]);
            break;
        case 'get':
            unset($_GET[$key]);
            break;
        case 'cookie':
            unset($_COOKIE[$key]);
            break;
        case 'files':
            unset($_FILES[$key]);
            break;
    }
    unset($self->$dataSource->$key);

非常感谢任何更明智的建议:)

试试这个:

//Url 
//?dangerous=yes&safe=keep

class MyClass {

    public static function _unset($datasource, $key) {
        global $$datasource;
        unset(${$datasource}[$key]);
    }

}

MyClass::_unset('_GET', 'dangerous');

//Test
print_r($_GET);

您缺少 global 关键字。