2016-02-12 3 views
2

Как я могу присвоить объекту новое свойство, используя переменную в качестве нового свойства?Назначить свойства одного объекта другим

Следующая дает мне объект свойства, необходимые:

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; 
} 
+1

'$ property ['id'] = $ id;' это массив? и как насчет '$ numeric_features', как он организован? ключевой объект? массив? – Webinan

+0

@Webinan Нет, они оба являются объектами, они имеют как результат красноречивого db-запроса. –

ответ

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) 
} 
+0

Отлично, только то, что я искал. –