1

I have a PHP Class which requires a unique value in its constructor. If multiple instances of the same class are passed the same value the results are horrific.

How would I go about detecting other instances of a Class so I can check and prevent this from happening before constructing any new ones?

1

2 Answers 2

4

A simple solution would be to keep a static array of the values inside the class. Then, when a new instance is created, check the static array's contents in the constructor.

Something like..

class Foo {
    private static $usedValues = array();

    public function __construct($val) {
        if(in_array($val, self::$usedValues)) {
            throw new Exception('blah');
        }

        self::$usedValues[] = $val;
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

+1 I was just about to write the same thing. Here's another implementation example.
So simple yet so clever, thanks! I knew static existed for a reason :D
2

I think the multiton pattern is right for you.

class Foo {
    static protected $_instances = array();
    static public function getInstance($id) {
        if(!self::exists($id)) {
            self::$_instances[$id] = new Foo($id);
        }
        return self::$_instances[$id];
    }
    static public function exists($id) {
        return isset(self::$_instances[$id]);
    }
    protected function __construct($id) {
    }
}

7 Comments

@MarkBaker, @Rudolph, I don't think this is actually a correct answer. First of all, shouldn't $_instances be static? Second, it seems that OP wants to know if an instance already exists with that ID - not just retrieve it if it exists.
Thank, I just spotted that error myself and corrected it. I'm guessing that what I wrote is what he really needs, but a static public exists($id) method is written pretty easily.
Thanks, this pattern is interesting me. But I am confused because the outcome seems to be new Foo($id) but if this is called in the constructor then doesn't this recreate an instance of itself and attempt to check it again? Seems kind of wasteful to run the script twice and construct two instances to perform this check, unless I am mistaken?
@GEorge, no it doesn't create two instances, because the getInstance() method is called statically.... static calls (and that includes the exists() method as well) don't create a new instance unless explicitly via "new"
It isn't called in the constructor. The custructor is deliberately left empty and set to protected/private so it can only be called from within the class - getInstance().
|

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.