[英]Accessing $_SESSION / $_GET / … with dynamic variable
我有一個負責所有與用戶相關的數據的類。 在我的一種方法中,我要訪問$_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'}
起作用${'_' . 'SESSION'}
${'_' . 'SESSION'}
? 以及如何實現我的目標: ${'_' . strtoupper($dataSource)}
${'_' . 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
關鍵字。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.