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);
}
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With