jaggy
jaggy

Reputation: 822

Dynamically edit nested PHP object attributes

Let's say I have an array array(container, article, title) and a value "Hello, is it me you're looking for?"

Now I want to set the attribute of a given object $target.

Now, what I want to happen is:

//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?';

Is this any way possible? Thanks!

Upvotes: 0

Views: 73

Answers (1)

VoteyDisciple
VoteyDisciple

Reputation: 37803

How about...

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

Upvotes: 1

Related Questions