Foreach/loop behavior with Objects

Can objects be used in foreach loops in the follow way? Or do I need to unset them?

I have a list of users. I want to update all of their names in a database which I do via the Member class. I am wondering what the best way to do this is.

foreach ($listOfMembers as $memberName) {
	$member = new Member();
	$member->setName($memberName)
	$member->Save();
}

Would it also work if I took the creation of the object out of the loop? My guess is it wouldn’t, but I don’t know about the behavior of objects in foreach loops so I am not sure.

$member = new Member();

foreach ($listOfMembers as $memberName) {
	$member->setName($memberName)
	$member->Save();
}

I get errors iterating over objects often (new to OOP) so I want to clear up this situation.

Thanks for all advice here.

Whoops - forgot a semi colon on this line:

$member->setName($memberName);

Sorry to anyone who was trying to figure out what I was doing there!

There are quite a few errors in my first post, sorry.

I want to know which one of these ways is the best way to iterate through an array ($listOfMembersNames) and use the member class to save the name.

Here is example 1:

foreach ($listOfMembersNames as $memberName) {
    $member = new Member();
    $member->setName($memberName);
    $member->Save();
}  

Here is example 2:


$member = new Member();
foreach ($listOfMembers as $memberName) {
    $member->setName($memberName);
    $member->Save();
}  

The difference is whether the member class is instantiated as an object before the loop or during it.
It’s also a question about the best way to iterate over objects in general. I am not used to objects acting like a container for information, so working with them in loops is unintuitive for me right now. I don’t know what to be considerate of. I am new to OOP. I hope that is clearer.

Just think about what is happening and it might be clearer. Let’s assume you have 10 names in $listOfMembers

In your first example, you make a new Member, set the name, and save it. This happens 10 times.

In the second example, you make a new Member one time, then set the name and save it 10 times. So here you have only one Member and you’ve changed his name ten times.

So example #1 would be the way to go. And you don’t have to unset the variable inside the loop. When it assigns the new Member at the top of the loop, it effectively unsets the old one. Side note: After the loop, though, you will still retain a reference to the last Member created so you could either unset $member at that point or just be careful how you use that variable.