Variable Variables Pointing to Arrays or Nested Objects

后端 未结 5 1569
南方客
南方客 2020-12-04 03:01

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

5条回答
  •  自闭症患者
    2020-12-04 03:30

    Nope you can't do that. You can only do that with variable, object and function names.

    Example:

     $objvar = 'classObj';
     var_dump(${$OBJVarVar}->var);
    

    Alternatives can be via eval() or by doing pre-processing.

    $arrayTest = array('value0', 'value1');
    $arrayVarTest = 'arrayTest[1]';
    
    echo eval('return $'.$arrayVarTest.';');
    eval('echo $'.$arrayVarTest.';');
    

    That is if you're very sure of what's going to be the input.

    By pre-processing:

    function varvar($str){
      if(strpos($str,'->') !== false){
        $parts = explode('->',$str);
        global ${$parts[0]};
        return $parts[0]->$parts[1];
      }elseif(strpos($str,'[') !== false && strpos($str,']') !== false){
        $parts = explode('[',$str);
        global ${$parts[0]};
        $parts[1] = substr($parts[1],0,strlen($parts[1])-1);
        return ${$parts[0]}[$parts[1]];
      }else{
        return false;
      }
    }
    
    $arrayTest = array('value0', 'value1');
    $test = 'arrayTest[1]';
    echo varvar($test);
    

提交回复
热议问题