2014-06-26 117 views
0

比方說,我有一個數組array(container, article, title)和值"Hello, is it me you're looking for?"動態編輯嵌套的PHP對象屬性

現在我想成立一​​個給定對象$target的屬性。

現在,我希望發生的是:

//from 
$levels = array(container, article, title); 
$target->container->article->title = 'Hello World'; 

// logic 
changeAttribute($target, $levels, "Hello, is it me you're looking for?"); 

//to 
echo $target->container->article->title; // 'Hello, is it me you're looking for?'; 

這是任何可能的方式?謝謝!

+0

請告訴我你的問題呢? –

回答

1

......怎麼

function changeAttribute(&$target, $levels, $value) { 
    $current = $target; 
    foreach($levels as $key) { 
     $current =& $current->$key; 
    } 
    $current = $value; 
}