【发布时间】:2016-06-18 14:03:50
【问题描述】:
我有一个处理所有与用户相关的数据的类。
在我的一种方法中,我想访问$_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);
非常感谢任何更聪明的建议:)
【问题讨论】:
-
嗯,有什么办法可以解决吗?
-
做一个 if 或 switch 语句来决定你需要哪个超全局。
-
我明白了,谢谢。我可以做到,但我希望找到更好的东西! :)
标签: php dynamic-variables