简体   繁体   English

Codeigniter中的多个类

[英]Multiple classes in Codeigniter

I want to create an array of objects, so what I did was to create a library but I can't figure out how to actually dynamically create instances of it in a loop and store each instance in an array. 我想创建一个对象数组,所以我要做的是创建一个库,但是我不知道如何在循环中实际动态创建它的实例并将每个实例存储在一个数组中。 Can anyone tell me please? 谁能告诉我?

To create 100 objects, you just need to loop from 0 to 99, creating an object every time and storing it in the array. 要创建100个对象,您只需从0到99循环,每次创建一个对象并将其存储在数组中。

class Foo { ... }

$fooArray = array();
for ($i = 0; $i < 100; $i++) {
    $fooArray[] = new Foo();
}

I'm not sure what this question has to do with CodeIgniter. 我不确定这个问题与CodeIgniter有什么关系。 Is there more you're not mentioning? 还有更多您没有提到的吗?

By design, loading a CodeIgniter library can only be done once. 通过设计,加载CodeIgniter库只能执行一次。 Subsequent attempts to load the same library are ignored. 随后加载相同库的尝试将被忽略。 You can (in a way) get around this by telling CI to instantiate the class with a different name every time you load another copy of the library (see the answer to this question ) 您可以(通过某种方式)通过告诉CI每次加载该库的另一个副本时使用不同的名称实例化该类来解决此问题 (请参阅此问题的答案)

A better solution is probably to create your class yourself, instead of using CI's library loading mechanism. 更好的解决方案可能是自己创建类,而不是使用CI的库加载机制。 That way you can create and store as many copies as you need. 这样,您可以创建和存储所需数量的副本。

EDIT: I'd suggest leaving the class in the libraries directory, and just using PHP's include() to make it available to your models/controllers where needed. 编辑:我建议将类保留在库目录中,仅使用PHP的include()使它在需要时可用于您的模型/控制器。

As for accessing CodeIgniter from within your class, you can do it using the following code: 至于从您的类中访问CodeIgniter,您可以使用以下代码进行操作:

$CI =& get_instance();

$CI->load->helper('url');
$CI->load->library('session');
$CI->config->item('base_url');

The get_instance() function returns the CodeIgniter super object, and once it's assigned to the $CI variable, you can access any of CI's methods just like you would from within a model or controller, except using $CI instead of $this. get_instance()函数返回CodeIgniter超级对象,并将其分配给$ CI变量后,就可以像在模型或控制器内一样访问CI的任何方法,只是使用$ CI代替$ this。 See this link for more information. 有关更多信息,请参见此链接

Please, check this link: I think is the best way to do it: 请检查此链接:我认为这是最好的方法:

Creating an object from a class in Codeigniter 从Codeigniter中的类创建对象

It uses Code Igniter code, but it let you use the "new" word, like any other OOP application. 它使用Code Igniter代码,但与其他任何OOP应用程序一样,它允许您使用“新”字。

I hope this help you. 希望对您有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM