简体   繁体   中英

Magic method get and set values dynamically from array

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'

The correct way is:

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

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

echo $this->obj->name;

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'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM