Welcome Guest, Not a member yet? Register   Sign In
Loading a library in a loop
#1

[eluser]asyafrudin[/eluser]
Hi.

I realized that if I wanted to use a 3rd party class in CodeIgniter, I have to use it as part of CodeIgniter's library. It happens that the class I'm using will be used inside a loop. Here's the snippet:

Code:
for ($i = 0; $i < some_number; $i++)
{
    $obj = new Myclass();
    //Codes using $obj ...
}

Knowing that loading a class in CodeIgniter means loading a library, the above code should look like this:

Code:
for ($i = 0; $i < some_number; $i++)
{
    $this->load->library('Myclass');
    //Codes using $this->myclass ...
}

But then I realize both code does not do the exact same thing. The first code will create a new instance of Myclass for each iteration, but it's not like that with the second code. It seems that in the second, the library will actually be loaded only in the first iteration.

The above results in unexpected behavior because I really need to load a new object for each iteration. Is there any way to make sure that the second code actually creates a new $this->myclass object?

Thanks for the help.
#2

[eluser]Sudz[/eluser]
load the library only once.
If you want to create object
call the constructor of your class in the loop.
#3

[eluser]asyafrudin[/eluser]
[quote author="Sudhakar Prajapati" date="1304510792"]load the library only once.
If you want to create object
call the constructor of your class in the loop.[/quote]

Thanks for the reply. Just to make things clear, isn't loading the library means calling the constructor?

Thanks again.
#4

[eluser]n0xie[/eluser]
Loading means including the library, then instantiating the object. There is nothing preventing you from instantiating another object

Code:
$this->load->library('Myclass');

for ($i = 0; $i < some_number; $i++)
{
    $foo = new Myclass();
}
#5

[eluser]asyafrudin[/eluser]
[quote author="n0xie" date="1304516320"]Loading means including the library, then instantiating the object. There is nothing preventing you from instantiating another object

Code:
$this->load->library('Myclass');

for ($i = 0; $i < some_number; $i++)
{
    $foo = new Myclass();
}
[/quote]

Okay then. I'll give it try. Thanks for the help.




Theme © iAndrew 2016 - Forum software by © MyBB