Dylan
Dylan

Reputation: 9373

PHP: set class array properties with a string as the propertyname

I have a class with a property that is an array:

  class NewObject {
    public $Props = array();
  }

  $obj = new NewObject();

  $obj->Props[0] = 'a';
  $obj->Props[1] = 'b';

Now I want to change the values of Props, not directly, but with a variable 'propertyname': This DOES work for single string properties but not for arrays, because the key N is interpreted as the Nth letter of the STRING 'Props' instead of the Nth value in the array!

  $propertyname = 'Props';

  $obj->$propertyname[0] ='c';   //doesnt work as expected, it tries to set $obj->P now, it seems
  $obj->$propertyname[1] ='d';

Any way to solve this ?

Upvotes: 1

Views: 2581

Answers (1)

zerkms
zerkms

Reputation: 254926

$obj->{$propertyname}[0] ='c';

Upvotes: 5

Related Questions