如何使用变量作为新属性为对象提供新属性?
以下为我提供了所需的属性对象:
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;
}
答案 0 :(得分:1)
查看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)
}