[英]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. 我有一个使用像get和set这样的魔术方法的类。 What I want is to use the property of an array as set "name", for later access the property using get "name".
我想要的是使用数组的属性作为设置“名称”,以便以后使用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. PHP实际上非常适合魔术方法,这看起来像是一种语法。 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'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.