views:

21

answers:

1

I have a class that's similar to the following:

class Person
{
    private static $_sqlData;

    public function __construct($id)
    {
        if (!self::$_sqlData)
        {
        self::$_sqlData = // GET THE DB STUFF
        }
    }

    public function getName()
    {
        return self::$_sqlData['name'];
    }
}

This has been working fine until I needed to place it in a loop.

foreach ($ids as $id)
{
    $person = new Person($id);
    echo $person->getName();
}

This continues to return the first persons name rather than all the names for the given IDs. The reason being the static variable. I've overcome this by adding in a __destruct() function to set $_sqlData to false then calling unset() on $person in the foreach() loop.

Is this a good way of handling this? Should I be approaching this differently?

+2  A: 

Why are you using a static variable? Is there something that you need this for? It seems like not using a static var for the $_sqlData, just using an instance variable, would give you the same result, unless there is something your not showing us.

A instance variable will destruct, just like you are doing manually to your static variable.

karlw