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?

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.