[FINAL EDIT]
Seems like I've been missing an important Warning contained in Variables variable PHP Manual http://www.php.net/manual/en/language.variables.variable.php :
Please note that variable variables cannot be used with PHP's Superglobal arrays within functions or class methods. The variable $this is also a special variable that cannot be referenced dynamically.
[ORIGINAL QUESTION]
I've encountered a problem trying to set/get html/server variables $_POST, $_GET, $_SESSION etc.. dynamically using a variable to hold it's name :
// Direct name
${'_GET'}['test'] = '1';
// Variable-holded name
$varname = '_GET';
${$varname}['test'] = '2';
echo "value is " . $_GET['test'];
will output :
value is 1
any idea why?
[EDIT 1] This is why I want to use it this way :
class Variable {
protected static $source;
public function __get($key) {
// Some validation / var manip needed here
if ( isset( ${self::$source}[$key] ) ) {
return ${self::$source}[$key];
}
}
public function __set($key, $value) {
// Some validation / var manip needed here too
${self::$source}[$key] = $value;
}
}
final class Get extends Variable {
use Singleton;
public static function create() {
parent::$source = "_GET";
}
}
final class Post extends Variable {
use Singleton;
public static function create() {
parent::$source = "_POST";
}
}
final class Session extends Variable {
use Singleton;
public static function create() {
parent::$source = "_SESSION";
}
}
create is called in the singleton constructor when instanciated
[EDIT 2] using PHP 5.4.3
$var = empty($_POST) ? $_GET : $_POST;and then work with$var.$_REQUEST. Well, it actually does more than just that... But 99.9% time you are not passing the same variable through both get, post and cookie, right? :)$_REQUESTsome days ago and my brain still does not have it in cache : ) Thanks for highlighting it.