通过另一个声明一个类变量


Declare one class variable via another

很抱歉标题含糊不清。。。我有一个php4类的问题,它似乎很难用语言表达。

我的类有一个"possibleValues"数组,该数组包含可以从外部更改的某些属性可以接受的值类型的信息。在下面的伪代码示例中,您可以看到我的属性共享相同的可接受值(颜色)。显然,我的代码中的$this->colors失败了,因为你不能通过另一个类变量定义一个类(对吗?)。

我该如何设置一个可以像这样引用的公共颜色数组,这样我就不必对允许相同值的不同字段重复相同的有效选项?

Class MyTest {
    var $colors = array('red', 'yellow', 'blue');
    var $possibleValues = array(
        'someAttribute',               array(0,1),
        'someEmotions',                array('happy, 'sad'),
-->     'someColorableAttribute',      $this->colors,
-->     'someOtherColorableAttribute', $this->colors,
     );
    ...
}

为了回答您的问题,您应该在构造函数中设置变量。在PHP4中,你真的不应该使用它,构造函数应该有类的名称。

function MyTest()
{
   $this->var = $this->colors;
}

如果你不想在构造函数中设置$possibleValues,你可以尝试这种方法:

PHP 4

class MyTest {
    var $colors = array('red', 'yellow', 'blue');
    var $possibleValues = array(
        'someAttribute' =>             array(0,1),
        'someEmotions'  =>             array('happy', 'sad'),
        'someColorableAttribute' =>    'colors',
        'someOtherColorableAttribute' => 'colors',
     );

    function getPossibleValues($attr) {
        //no attribute, empty list
        if (!array_key_exists($attr, $this->possibleValues))
            return array();
        $possible_values = $this->possibleValues[$attr];
        //value is a string, check for object variable with such name
        if (is_string($possible_values)) {
            if (!array_key_exists($possible_values, get_object_vars($this)))
                return array();
            return $this->$possible_values;
        }
        return $possible_values;
    }
}
$a = new MyTest();
var_dump($a->getPossibleValues('someAttribute'));
var_dump($a->getPossibleValues('someEmotions'));
var_dump($a->getPossibleValues('someColorableAttribute'));
var_dump($a->getPossibleValues('someOtherColorableAttribute'));

我使用get_object_vars,因为在PHP4中不存在property_exists

PHP 5(类常量)

class MyTest {
    const COLORS = 'red|yellow|blue';
    private $possibleValues = array(
        'someAttribute' =>             array(0,1),
        'someEmotions'  =>             array('happy', 'sad'),
        'someColorableAttribute' =>    self::COLORS,
        'someOtherColorableAttribute' => self::COLORS,
     );

    public function getPossibleValues($attr) {
        //no attribute, empty list
        if (!array_key_exists($attr, $this->possibleValues))
            return array();
        $possible_values = $this->possibleValues[$attr];
        //value is a string, explode it around |
        if (is_string($possible_values)) {
            return explode('|', $possible_values);
        }
        return $possible_values;
    }
}