note 69539 deleted from language.variables.variable by danbrown

From: Date: Wed, 24 Jun 2009 16:52:19 +0000
Subject: note 69539 deleted from language.variables.variable by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-157393@lists.php.net to get a copy of this message
Note Submitter: Typer85 at gmail dot com ---- In regards to using variables variables on a variable of type array; I found that when using variable variables on a SuperGlobal such as $_POST or $_GET, which are in essense arrays, PHP refuses to access their elements, instead complaining that an undefined variable exists. This is evident even with the little tweaks to below. For example, using "mot at tdvniikp dot ru" tweak below ( thanks you saved a lot of trouble ) variable Variable SuperGlobals worked great. ---------------------------------------- <?php $superGlobal = '_POST'; global $$superGlobal; print_r( $$superGlobal ); ?> ---------------------------------------- The above code will with success provide an output of every key in the $_POST SuperGlobal along with its values. But here is where the problem comes in. What if I wanted to access a key from the variable variable, as illustrated in the following example. ---------------------------------------- <?php $superGlobal = '_POST'; global $$superGlobal; // This Would Not Work! echo $$superGlobal[ 'Name' ]; ?> ---------------------------------------- As you can see, I am assuming that a key in the $_POST SuperGlobal by the name of 'Name' exists, possibly from a form submission. Here is the problem; PHP will fail to access this key. You will get an E_NOTICE error that an undefined variable exists. Notice I said an UNDEFINED VARIABLE, not UNDEFINED INDEX. PHP will assume that there is no such variable named $_POST at all. I do not know if this is a bug or is intended but I found a quick workaround. The workaround is simple. Instead of opting to access a key from the variable variable SuperGlobal, you simply just copy the contents of the variable variable into a normal variable. Then opt to use it as you would normally. The following example shows what I mean. ---------------------------------------- <?php $superGlobal = '_POST'; global $$superGlobal; /* * By assigning our variable variable in a normal non * dynamic variable, we can now access array keys * with no problem. */ $newSuperGlobal = $$superGlobal; // This Would Now Work :). echo $newSuperGlobal[ 'name' ]; ?> ---------------------------------------- I will assume that this concept applies to not only variable variable SuperGlobals, but variable variable arrays in general, since like I pointed out before, most SuperGlobals are in essense arrays. I hope this saved people some trouble.

« previous php.notes (#157393) next »