PHP $_GET/$_POST via variable variables

做~自己de王妃 提交于 2019-12-01 06:37:34

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.

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

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.

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.

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.

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;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!