PHP - 从同一个 class 中的另一个 class 变量设置 class 变量?

PHP - Set class variable from another class variable within same class?

我正在尝试设置 PHP class:

class SomeClass {
    private $tags = array(
        'gen1' => array('some string', 1), 
        'gen2' => array('some string', 2), 
        'gen3' => array('some string', 3), 
        'gen4' => array('some string', 4), 
        'gen5' => array('some string', 5), 
    );

    private $otherVar = $tags['gen1'][0];
}

但这会引发错误:

PHP Parse error: syntax error, unexpected '$tags'

正在将其切换到通常...

private $otherVar = $this->tags['gen1'][0];

returns同样的错误:

PHP Parse error: syntax error, unexpected '$this'

但是在函数内访问变量没问题:

private $otherVar;

public function someFunct() {
    $this->otherVar = $this->tags['gen1'][0];
}

如何使用之前定义的class变量来定义和初始化当前变量,而不需要额外的功能?

做你想做的最接近的方法是将赋值放在构造函数中。例如:

class SomeClass {
    private $tags = array(
        'gen1' => array('some string', 1), 
        'gen2' => array('some string', 2), 
        'gen3' => array('some string', 3), 
        'gen4' => array('some string', 4), 
        'gen5' => array('some string', 5), 
    );

    private $otherVar;

    function __construct() {
         $this->otherVar = $this->tags['gen1'][0];
    }

    function getOtherVar() {
        return $this->otherVar;
    }
}

$sc = new SomeClass();
echo $s->getOtherVar(); // echoes some string