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
  • 1
    nope, $item is value, $arr is just a flat array, so its effectively, $this->obj->value Commented Apr 20, 2016 at 0:39

2 Answers 2

1

The correct way is:

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

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

echo $this->obj->name;
Sign up to request clarification or add additional context in comments.

3 Comments

Why the braces {$attribute} ?
That is the correct way for dynamically declare object attributes
I don't think this is true, the braces just allow you to evaluate an expression before trying to access it. See PHP Reference so ->$item['name'] and ->{$item['name']} are functionally different, but ->$item and ->{$item} are the same, since there is no ambiguity.
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'

1 Comment

Got that a few seconds ago :) Thanks anyway! Will state that as correct shortly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.