我尝试使用 $this->$arrDataName[$key]
访问数组 $this-> 中具有键
.但是 PHP 解释错误。$key
的元素$arrDataName
我在 $arrDataName
到 $this->{$arrDataName}[$key]
周围用 { }
试过了,但是它不起作用。
在 php.net 上我找到了一个建议,但我无法实现。
In order to use variable variables with arrays, you have to resolve an ambiguity problem. That is, if you write $$a[1] then the parser needs to know if you meant to use $a[1] as a variable, or if you wanted $$a as the variable and then the [1] index from that variable. The syntax for resolving this ambiguity is: ${$a[1]} for the first case and ${$a}[1] for the second.
也许任何人都可以帮助我。
谢谢!
编辑:
我觉得不行,但是我忘了填充数组。
最后它起作用了。 :)
这是解决方案:$this->{$arrDataName}[$key]
最佳答案
你的语法是正确的:
$this->{$varName}[$key]
你也可以为此使用一个额外的变量:
$myTempArr = $this->$arrDataName;
$myTempArr[ $key ];
恕我直言,那样可读性更好...
关于php - 动态访问 PHP 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3235632/