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?
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.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.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 therequest_order
setting, but the default is just$_GET
and$_POST
.Superglobals cannot be referenced as variable variables inside of classes or methods, so this will work:
But this will not:
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.you can do this but dont know if it is a good coding practice