Foreach loop that creates an object

I have a requirement to accept an array of checked items from a table and update the field based on which items were selected. At first, I thought about where to simply scroll through each of these elements in an array and access a function in a particular class to update the state.

I'm a little worried about this approach, as that would mean creating an instance of the object for each iteration of the loop to update the corresponding status.

foreach($example as $exampleId){
    $newExample=new Example($exampleId);
    $newExample->updateStatus('active');
}

Are there any better ways? This seems like bad practice, but I'm struggling to find an alternative way.

+3
source share
2 answers

- is that an option?

$newExample=new Example();
foreach($example as $exampleId){
    $newExample->updateStatus($exampleId,'active');
}

:

foreach($example as $exampleId){
    $newExample=new Example($exampleId);
    $newExample->updateStatus('active');
    $newExample->__destruct(); 
    unset($newExample);
}

anothe

$newExample=new Example();
foreach($example as $exampleId){
    $newExample->set_example_id($exampleId);
    $newExample->updateStatus('active');
}
+3

, , - ? Example, , ? :

foreach($example as $exampleId){
    Example::UpdateExampleStatus($exampleId,'active');
}
+1

Source: https://habr.com/ru/post/1757659/


All Articles