phpvariable-variablesobject-properties

Variable Variables Pointing to Arrays or Nested Objects


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?


Solution

  • Array element approach:

    The code:

    $arrayTest  = array('value0', 'value1');
    $variableArrayElement = 'arrayTest[1]';
    $arrayName  = substr($variableArrayElement,0,strpos($variableArrayElement,'['));
    $arrayIndex = preg_replace('/[^\d\s]/', '',$variableArrayElement);
    
    // This returns the correct 'value1'
    echo ${$arrayName}[$arrayIndex];
    

    Object properties approach:

    The code:

    $variableObjectProperty = "classObj->obj";
    list($class,$property)  = explode("->",$variableObjectProperty);
    
    // This now return the values of $classObj->obj
    var_dump(${$class}->{$property});    
    

    It works!