Variable Variables Pointing to Arrays or Nested Objects

后端 未结 5 1580
南方客
南方客 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:39

    In echo $arrayTest[1]; the vars name is $arrayTest with an array index of 1, and not $arrayTest[1]. The brackets are PHP "keywords". Same with the method notation and the -> operator. So you'll need to split up.

    // bla[1]
    $arr = 'bla';
    $idx = 1;
    echo $arr[$idx];
    
    // foo->bar
    $obj = 'foo';
    $method = 'bar';
    echo $obj->$method;
    

    What you want to do sounds more like evaluating PHP code (eval()). But remember: eval is evil. ;-)

提交回复
热议问题