1

Iam sorry if this kind of question has been asked before, but I couldnt find anything according to my question.

I've got a class which uses magic method like get and set. What I want is to use the property of an array as set "name", for later access the property using get "name".

What I do now:

$arr = array('name' => 'value')
$this->obj->name = $arr['name'];

What I want and doesnt work as I try:

$arr = array('name' => 'value');

foreach($arr as $item)
   $this->obj->[$item] = $item['name'];

echo $this->obj->name; // result should be 'value'
  • 1
    nope, `$item` is `value`, `$arr` is just a flat array, so its effectively, `$this->obj->value` – Kevin Apr 20 '16 at 00:39

2 Answers2

1

The correct way is:

$arr = array('name' => 'value');

foreach($arr as $attributeName =>$value) {
  $this->obj->{$attributeName} = $value;
}

echo $this->obj->name;
John Diaz
  • 341
  • 3
  • 13
  • Why the braces {$attribute} ? –  Apr 20 '16 at 00:53
  • That is the correct way for dynamically declare object attributes – John Diaz Apr 20 '16 at 00:54
  • 1
    I don't think this is true, the braces just allow you to evaluate an expression before trying to access it. [See PHP Reference](http://php.net/manual/en/language.variables.variable.php) so ->$item['name'] and ->{$item['name']} are functionally different, but ->$item and ->{$item} are the same, since there is no ambiguity. – Waddles Apr 20 '16 at 01:03
0

PHP is actually pretty good with magic methods, this just seems like a syntactic thing. You should be able to do what you're after with just

foreach ($arr as $key => $item) 
    $this->obj->$key = $item;

echo $this->obj->name; // Results in 'value'
Waddles
  • 196
  • 2
  • 7
  • Got that a few seconds ago :) Thanks anyway! Will state that as correct shortly. –  Apr 20 '16 at 00:48