从另一个对象分配一个对象属性
问题描述:
如何使用变量作为新属性为对象提供新属性?从另一个对象分配一个对象属性
下给我所需要的属性对象:
switch ($property['property_type']):
case 'Residential':
$property = $this->property
->join('residential', 'property.id', '=','residential.property_id')
->join('vetting', 'property.id', '=', 'vetting.property_id')
->where('property.id', $id)
->first();
$property['id'] = $id;
break;
default:
return Redirect::route('property.index');
break;
endswitch;
下面给我的属性和值的列表:
$numeric_features = App::make('AttributesController')->getAttributesByType(2);
这里的问题是,如何动态地添加各$numeric_features
属性对象?
foreach ($numeric_features as $numeric_feature) {
***$this->property->{{$numeric_feature->name}}***=$numeric_feature->value;
}
答
看看http://php.net/manual/en/function.get-object-vars.php
$property_names = array_keys(get_object_vars($numeric_features));
foreach ($property_names as $property_name) {
$property->{$property_name} = $numeric_features->{$property_name};
}
,并检查该EVAL结果,它增加了一个对象的属性到另一个对象: https://eval.in/517743
$numeric_features = new StdClass;
$numeric_features->a = 11;
$numeric_features->b = 12;
$property = new StdClass;
$property->c = 13;
$property_names = array_keys(get_object_vars($numeric_features));
foreach ($property_names as $property_name) {
$property->{$property_name} = $numeric_features->{$property_name};
}
var_dump($property);
结果:
object(stdClass)#2 (3) {
["c"]=>
int(13)
["a"]=>
int(11)
["b"]=>
int(12)
}
+0
完美,正是我所期待的。 –
'$ property ['id'] = $ id;'这是一个数组吗?以及'$ numeric_features'如何组织?键值对象?阵列? – Webinan
@ Webinan不,它们都是对象,它们都具有雄辩的db查询的结果。 –