我们说我有一个数组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?';
这有可能吗?谢谢!
答案 0 :(得分:1)
怎么样......
function changeAttribute(&$target, $levels, $value) {
$current = $target;
foreach($levels as $key) {
$current =& $current->$key;
}
$current = $value;
}