Nick
Nick

Reputation: 11384

Access array property member with variable property name

In the context of a class method, what syntax is used to get the value of a array member using a variable property name?

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];    
   }
}

This syntax:

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

...isn't quite right though, because it tries to convert $this->$PropName to a string to use as a variable name.

This syntax:

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

... Tries to use the value of $PropName[$KeyName] as the property name which is also incorrect.

There must be some way to get PHP to evaluate $this->$PropName first, and then get the $KeyName from the resultign array (without the use of an intermediary variable)?

Upvotes: 1

Views: 45

Answers (2)

Stuart Miller
Stuart Miller

Reputation: 657

$Propname is not a property of $this but a local variable inside MyFunction() try:

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

Upvotes: 1

deceze
deceze

Reputation: 522024

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

This is the right approach, the only thing you need to do is delineate where your $PropName variable ends (i.e. whether it's $PropName or $PropName[$KeyName]). To do this, use:

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

Upvotes: 1

Related Questions