Is it possible to create a variable variable pointing to an array or to nested objects? The php docs specifically say you cannot point to SuperGlobals but its unclear (to me at least) if this applies to arrays in general.
Here is my try at the array var var.
// Array Example
$arrayTest = array('value0', 'value1');
${arrayVarTest} = 'arrayTest[1]';
// This returns the correct 'value1'
echo $arrayTest[1];
// This returns null
echo ${$arrayVarTest};
Here is some simple code to show what I mean by object var var.
${OBJVarVar} = 'classObj->obj';
// This should return the values of $classObj->obj but it will return null
var_dump(${$OBJVarVar});
Am I missing something obvious here?
In
echo $arrayTest[1];
the vars name is$arrayTest
with an array index of1
, and not$arrayTest[1]
. The brackets are PHP "keywords". Same with the method notation and the->
operator. So you'll need to split up.What you want to do sounds more like evaluating PHP code (
eval()
). But remember: eval is evil. ;-)Array element approach:
$arrayName
.$arrayIndex
.The code:
Object properties approach:
$class
and$property
.var_dump()
The code:
It works!
Nope you can't do that. You can only do that with variable, object and function names.
Example:
Alternatives can be via eval() or by doing pre-processing.
That is if you're very sure of what's going to be the input.
By pre-processing:
Use
= &
to assign by reference: