PHP $_GET/$_POST via variable variables

2019-02-18 04:46发布

问题:

I'm attempting to dynamically access both the $_GET and $_POST arrays, among others, using variable variables. The reason I'm trying to do this is so that I can perform similar actions on multiple arrays without needing to declare specific iterations for each. I'm reasonably sure this is possible, as PHP's documentation says it is able to use variable variables to dynamically access an array, however I'm unable to get it to work. A simple demonstration is when I'm attempting to verify that a certain property has been set.

if(isset(${$this->_array}[$property])) { return ${$this->_array}[$property]; }
else { return null; }

When I run the above script I always get null, however when I statically seek the desired property, manually using $_GET or $_POST, I get the desired outcome. I have triple checked $this->_array and $property and they are returning the correct string values. Are these arrays unavailable for such access, or am I doing something wrong?

回答1:

Superglobals (such as $_POST) can not be used as variable variables within functions.

You could say something like $post = $_POST; and then use 'post' and it'd work, but directly using '_POST' won't.



回答2:

Superglobals cannot be referenced as variable variables inside of classes or methods, so this will work:

<?php
$var = "_GET";
print_r(${$var});

But this will not:

<?php
test();
function test() {
  $var = "_GET";
  print_r(${$var});
}

I suspect that there is a better way to do what you are trying to accomplish.

http://php.net/manual/en/language.variables.superglobals.php#refsect1-language.variables.superglobals-notes



回答3:

Whatever you're doing wrong, using variable variables is probably making it worse. For your own sanity, please stop. They should never be deployed in production code under any circumstances. They're impossible to debug, and using them in your code is like trying to read something that someone else wrote with their feet. If they have particularly dexterous feet, then perhaps you can understand what they're doing. But 99.9999% of the time, it is better to just use normal arrays.

That being said, try $_REQUEST instead.



回答4:

There's already an array that contains both $_GET and $_POST. It's named $_REQUEST. Having said that, it can also contain the contents of $_COOKIE depending on the request_order setting, but the default is just $_GET and $_POST.



回答5:

You say you want to access both the $_GET and $_POST arrays, among others -- what are these 'others'? You can use $_REQUEST to check the contents of $_GET, $_POST, and $_COOKIE all at once.



回答6:

you can do this but dont know if it is a good coding practice

if( $_SERVER['REQUEST_METHOD'] == 'POST' ) {
     $method = '_POST';
 }
 else {
    $method = '_GET';
 }
 $data = $$method;