views:

60

answers:

4

I am currently battling this error message by refactoring some of my code:

Fatal error: Allowed memory size of 33554432 bytes exhausted

I figure I must have sloppy code somewhere. Is it a bad practice to load new models in a loop like so:

<?php 
foreach($blog_ids as $blog_id) { 
    $blog = new Blog($blog_id);
    echo $blog->title;
}
?>

Is this a quick way to burn up memory....and if it is, how do I accomplish the same goal?

EDIT:

  1. the above code is just a snippet. I have tons of info for each blog - a model should most likely be the best way to handle it.

  2. I may have up to 100 different blog listings on a page.

+2  A: 

Your $blog variable is reused every time, so PHP's garbage collector should free the previous Blog instance's memory for you. Check memory_get_usage() inside of the loop to see if it doesn't.

janmoesen
The previous isnt freed from memory, otherwise he cant print the blog title. I think after each time he is finished the work, he should call the __destructor manualy in the loop
streetparade
Why shouldn't he be able to print the blog title of the **current** one if the **previous** one is freed?
lamas
+1  A: 

I was also having this problem with my models, where I needed to instantiate a lot of them to get one or two informations per record.

My solution was to create a Collection class, something along this:

class BlogCollection
{
    public function getTitles()
    {
        // select and returns just the titles of blogs
    }
}

This way you get the information you want in a centralized way and don´t need to load full models just to get one or two informations.

Luiz Damim
A: 

I don´t know what is happening in the constructor of Blog but I imagine you are filling up your object with information from a database.

Apart from getting more information than you need (if you only need the title...), you are possibly also making a lot of trips to the database if you can have up to 100 entries that you need to display.

What I would do is create a static function that gets the whole collection of titles (and whatever else you need) all at once and store that in an array to display afterwards.

jeroen
A: 

When you comment out that loop, are you still getting this error?

Trav