Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

instantiating a new class in a loop or not in a loop?

require_once('Class.php');
$myArray = array(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15); // etc

which is correct?

foreach($myArray as $key => $val) {
    $class = new Class();
    $result = $class->someMethod($val);
}

or

$class = new Class();
foreach($myArray as $key => $val) {
    $result = $class->someMethod($val);
}

Edited to be more specific, using http://simplepie.org/wiki/reference/simplepie/get_items

$aFeeds = array(rssFeed1,rssFeed2,rssFeed3,...);
foreach($aFeeds as $key => $feedURL) {
    $feed->set_feed_url(feedURL);
    $feed->init();
    $feed->get_items(0, 5);
}
like image 937
ed209 Avatar asked Feb 28 '23 21:02

ed209


2 Answers

Short answer: that depends.

Long answer: If repeat instantiation doesn't change the outcome of the execution, then create the class only once outside of the loop.

If repeat instantiation does change the outcome of the execution, then creating the class instances inside the loop is the appropriate implementation.

Which of these is true depends entirely upon how your class is written. I'm willing to bet that you don't need to re-instantiate the class every iteration, but that's purely speculative.

like image 72
Peter Bailey Avatar answered Mar 07 '23 06:03

Peter Bailey


There is no correct, and not much will go wrong in either case. I assume they're functionally equivalent, as Class doesn't appear to have state.

like image 24
Derek Illchuk Avatar answered Mar 07 '23 07:03

Derek Illchuk