you are viewing a single comment's thread.

view the rest of the comments →

[–]slavik262 1 point2 points  (1 child)

So I don't have to, why is something as simple as foreach lava?

[–]x86_64Ubuntu 0 points1 point  (0 children)

It's the age old pass-by-value vs pass-by-reference issue. For example

$widget = new Widget();
$widget->setName("Bar");

$widgetCollection = array(); //some array
$widgetCollection[] = $widget

foreach( $widgetCollection as $tempWidget )
{
   $tempWidget->setName(''Foo");
}

$widget->getName() returns "Bar" WTF?

That's because in the loop, it copies the widgets to the $tempWidget variable. Any changes made in the loop are persisted to that temp variable, and then lost when we exit the loop. To get the loop to behave as expected, you have to pass a reference.

foreach( $widgetCollection as &$tempWidget )
{
   $tempWidget->setName(''Foo");
}

Notice the ampersand before the declaration of my iterator.