在循环中或不在循环中实例化新类? [英] instantiating a new class in a loop or not in a loop?

查看:356
本文介绍了在循环中或不在循环中实例化新类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

这是否正确?

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

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

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


推荐答案

取决于。

长回答:如果重复实例化

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.

这篇关于在循环中或不在循环中实例化新类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆