访问全局变量变量的问题

时间:2017-01-23 19:13:28

标签: php

我无法从函数中访问全局变量变量(作为关联数组):

$arr1 = array(
    1 => "Alex1",
    2 => "Blah",
    3 => "Charlie"
);

$arr2 = array(
    1 => "D",
    2 => "E",
    3 => "F"
);

function GetVal()
{
  $x = 1;  // But could be any value
  $dd = $GLOBALS[${'arr'.$x}];

$ouput = $dd[1];    // should be "Alex1"
}

给出通知:未定义的变量和注意:未定义的索引

1 个答案:

答案 0 :(得分:0)

$GLOBALS[${'arr'.$x}]转换为$GLOBALS[$arr1]$arr1在函数范围内不存在,加上它是一个数组。您需要获取一个arr1字符串作为索引:

$dd = $GLOBALS['arr'.$x]; // or use "arr$x"

转换为$GLOBALS['arr1']