views:

295

answers:

5
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%5Fitems

$aFeeds = array(rssFeed1,rssFeed2,rssFeed3,...);
foreach($aFeeds as $key => $feedURL) {
    $feed->set_feed_url(feedURL);
    $feed->init();
    $feed->get_items(0, 5);
}
A: 

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.

Derek Illchuk
+1  A: 

I can't really say unless I see what someMethod does. If it is purely functional, then the second sample would probably be the faster. If it affects the class members in some way, then there is a chance the two would lead to different results. None of them is 'wrong' though.

Yacoby
+1  A: 

Most likely the second. But it depends on what exactly you're trying to do.

If you want to call someMethod on the same instance of the object each time (which is the likely situation), then the second method is the correct one. The second method is also preferable if it doesn't matter whether it's the same instance each time or not.

Only if you want it called on a different instance each time should the first method be used.

Anon.
+4  A: 

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.

Peter Bailey
A: 

The latter - it will improve performance as the class is only instantiated once. As far as state is concerned (see other answers), just try them both and compare the results.

Lucas Jones