Php 使用变量属性名访问数组属性成员

Php 使用变量属性名访问数组属性成员,php,Php,在类方法的上下文中,使用什么语法来获取使用变量属性名的数组成员的值 class { private $aFruits=array('Apple'=>'Red','Banana'=>'Yellow','Orange'=>'Orange'); public function MyFunction(){ $PropName = 'aFruits'; $KeyName = 'Banana'; // Should be able t

在类方法的上下文中,使用什么语法来获取使用变量属性名的数组成员的值

class {

   private $aFruits=array('Apple'=>'Red','Banana'=>'Yellow','Orange'=>'Orange');

   public function MyFunction(){

      $PropName = 'aFruits';
      $KeyName = 'Banana';

      // Should be able to do something like:
      // Expected result: 'Yellow'
      return ${$this->$PropName}[$KeyName];    
   }
}
此语法:

return ${$this->$PropName}[$KeyName];
return $this->$PropName[$KeyName];
但是…并不完全正确,因为它试图将
$this->$PropName
转换为字符串以用作变量名

此语法:

return ${$this->$PropName}[$KeyName];
return $this->$PropName[$KeyName];
。。。尝试使用
$PropName[$KeyName]
的值作为属性名,这也是不正确的

必须有某种方法让PHP首先计算
$this->$PropName
,然后从resultign数组中获取
$KeyName
(不使用中间变量)

这是正确的方法,您需要做的唯一一件事就是描述
$PropName
变量的结束位置(即它是
$PropName
还是
$PropName[$KeyName]
)。为此,请使用:

return $this->{$PropName}[$KeyName];

$Propname不是$this的属性,而是MyFunction()中的局部变量。请尝试:


NP,很高兴你把它整理好了。