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

2019-04-11 21:46发布

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);
}

5条回答
Anthone
2楼-- · 2019-04-11 21:46

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.

查看更多
再贱就再见
3楼-- · 2019-04-11 21:49

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.

查看更多
戒情不戒烟
4楼-- · 2019-04-11 22:02

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.

查看更多
ゆ 、 Hurt°
5楼-- · 2019-04-11 22:10

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.

查看更多
Animai°情兽
6楼-- · 2019-04-11 22:12

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.

查看更多
登录 后发表回答