Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Foreach loop which results in object instantiation

I have a requirement to accept an array of checked items from a table and update a field based on which items have been selected. Initially my thoughts where to simply loop over each of these items in the array and access a function in the specific class to update the status.

I'm slightly concerned about this approach as it would mean instantiating an object for each iteration of the loop in order to update the relevant status.

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

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


1 Answers

is this an option?

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

otherwise you could always do this:

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

for this you would need anothe method in your class

$newExample=new Example();
foreach($example as $exampleId){
    $newExample->set_example_id($exampleId);
    $newExample->updateStatus('active');
}
like image 72
Christian Smorra Avatar answered Jan 03 '26 14:01

Christian Smorra



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!