0

[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

6
  • Why to hell you want to set request variables' values???? They are not designed for that. :) Commented Feb 25, 2013 at 16:47
  • If you do not know whether to use GET or POST, you can use this: $var = empty($_POST) ? $_GET : $_POST; and then work with $var. Commented Feb 25, 2013 at 16:48
  • Aside from the dodgy getting of request variables, your code just ran completely fine for me :) Commented Feb 25, 2013 at 16:48
  • @fedorqui, and there's even a shorthand for that, called $_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? :) Commented Feb 25, 2013 at 16:51
  • Yes, right @J0HN! I discovered $_REQUEST some days ago and my brain still does not have it in cache : ) Thanks for highlighting it. Commented Feb 25, 2013 at 16:53

3 Answers 3

2

I'm guessing it has something to do with the fact that you shouldn't be assigning values to $_GET like that. Anyhow, this works just fine:

$source = '_GET';
echo ${$source}['test'];
// URL: http://domain.com/thing.php?test=yes
// output: "yes"

edit

Coincidentally, today I went back to update some old code where it looks like I was trying to implement exactly this inside of a class, and it wasn't working. I believe that using the global keyword before attempting to access a superglobal via a variable variable will solve your problem as well.

Class MyExample {
    private $method = '_POST';

    public function myFunction() {
        echo ${$this->method}['index']; //Undefined index warning
        global ${$this->method};
        echo ${$this->method}['index']; //Expected functionality
    }
}
Sign up to request clarification or add additional context in comments.

5 Comments

Yeah I got it to work, but I can't set vars this way. I was using it with _SESSION and it won't add/edit any values.
@user1990715 I can't think of a reason why it shouldn't work. If you can't get it working you might want to consider filing a bug about it.
This only works in global scope IIRC. Referencing the superglobals per ${} local scope access is hindered by the way they're referenced in other contexts.
@mcNdave I've updated my answer with something that should solve your problem.
@Sammitch I've updated my original question with the answer, it simply is impossible. Your solution works fine with Get and Post, but when you're trying to set a Session variable, it won't update the session itself. Still, I may use it for my Get Post and Globals, thanks !
1

You may be looking for variable variables. Taken from PHP.net:

<?php
$a = 'hello';
?>

<?php
$$a = 'world';
?>

<?php
echo "$a ${$a}";
//returns: hello world
//same as
echo "$a $hello";
?>

EDIT Another user on php.net had your exact question. Here is his answer.

<?php 
function GetInputString($name, $default_value = "", $format = "GPCS") 
    { 

        //order of retrieve default GPCS (get, post, cookie, session); 

        $format_defines = array ( 
        'G'=>'_GET', 
        'P'=>'_POST', 
        'C'=>'_COOKIE', 
        'S'=>'_SESSION', 
        'R'=>'_REQUEST', 
        'F'=>'_FILES', 
        ); 
        preg_match_all("/[G|P|C|S|R|F]/", $format, $matches); //splitting to globals order 
        foreach ($matches[0] as $k=>$glb) 
        { 
            if ( isset ($GLOBALS[$format_defines[$glb]][$name])) 
            {    
                return $GLOBALS[$format_defines[$glb]][$name]; 
            } 
        } 

        return $default_value; 
    } 
?>

1 Comment

Am I the only person that feels that code (1) ugly, (2) won't work?
0

Why not just use $_REQUEST which includes $_GET, $_POST and $_COOKIE? Or am I misunderstanding the purpose?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.