panthro
panthro

Reputation: 24061

Replacing an item in an object?

I'm looping through an object:

foreach ($data as $asset) {

    $asset->test = 'test';
}

test exists in $data and is set to something else, I wish to replace it with 'test'.

The above fails to work. Where am I going wrong?

Upvotes: 0

Views: 40

Answers (2)

Shotgun
Shotgun

Reputation: 678

You can think about using a function that already exists, like array_walk that would execute your function.

function test_exists(&$asset) {
    $asset->test = "test";
}

array_walk($data, "test_exists");

Upvotes: 0

Bora
Bora

Reputation: 10717

You should use referenced loop with & like foreach ($data as &$asset)

foreach ($data as &$asset) 
{
    $asset->test = 'test';
}

Referenced loop will have an effect to $data, otherwise only current $asset object changes.

Upvotes: 1

Related Questions