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

时间:2016-06-18 14:03:50

标签: php dynamic-variables

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

通过动态var如下(在_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);

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

1 个答案:

答案 0 :(得分:0)

试试这个:

//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关键字。