动态编辑嵌套的PHP对象属性

时间:2014-06-26 19:05:07

标签: php oop

我们说我有一个数组array(container, article, title)和一个值"Hello, is it me you're looking for?"

现在我想设置给定对象$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?';

这有可能吗?谢谢!

1 个答案:

答案 0 :(得分:1)

怎么样......

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