views:

66

answers:

3

I have a class with a static method. There is an array to check that a string argument passed is a member of a set. But, with the static method, I can't reference the class property in an uninstantiated class, nor can I have an array as a class constant.

I suppose I could hard code the array in the static method, but then if I need to change it, I'd have to remember to change it in two places. I'd like to avoid this.

+6  A: 

You can create a private static function that will create the array on demand and return it:

class YourClass {
    private static $values = NULL;
    private static function values() {
        if (self::$values === NULL) {
            self::$values = array(
                'value1',
                'value2',
                'value3',
            );
        }
        return self::$values;
    }
}
soulmerge
+1: very useful technique, I 've done this many times myself.
Jon
Can I populate the array and use it normally during instantiation?
Of course, that's possible. I generally implement it this way for large data sets to save memory for the case the class gets loaded, but the array isn't used.
soulmerge
A: 

I put arrays in another file and then include the file wherever I need it.

NatalieL
A: 

I am having a really really hard time understanding your question. Here is essentially what I understood:

I need to maintain a proper set, where no two elements are the same.

PHP does not have a set type, not even in SPL! We can emulate the functionality of a set but any solution I can think of is not pleasant. Here is what I think is the cleanest:

<?php

class Set {

    private $elements = array();

    public function hasElement($ele) {
        return array_key_exists($ele, $elements);
    }

    public function addElement($ele) {
        $this->elements[$ele] = $ele;
    }

    public function removeElement($ele) {
        unset($this->elements[$ele]);
    }

    public function getElements() {
        return array_values($this->elements);
    }

    public function countElements() {
        return count($this->elements);
    }

}

Example usage:

<?php

$animals = new Set;
print_r($animals->getElments());
$animals->addElement('bear');
$animals->addElement('tiger');
print_r($animals->getElements());
$animals->addElement('chair');
$animals->removeElement('chair');
var_dump($animals->hasElement('chair'));
var_dump($animals->countElements());
erisco
'No two elements are the same' is not critical functionality. I just need to make sure that an argument is a member of a set. A little repetition isn't a deal-killer; but thinking that something is a member when it shouldn't be is.
Well, sorry I could not help you. I could not understand, and still cannot understand, your question.
erisco