How can I get around without arrays as class constants in php?
I have a class with a static method. There is an array for checking that the passed string argument is a member of the set. But with a static method, I cannot reference a property of a class in an uninstalled class, and I cannot have an array as a class constant.
I suppose I could hardcode the array in a static method, but then if I need to change it, I will need to remember it in two places. I would like to avoid this.
a source to share
You can create a private static function that will create an 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;
}
}
a source to share
It is very difficult for me to understand your question. Here, in fact, I got it:
I need to maintain a correct set where the two elements are not the same.
PHP does not have a given type, even in SPL! We can emulate the functionality of the kit, but any solution I think I don't like. Here's 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);
}
}
Usage example:
<?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());
a source to share