2016-10-06 129 views
1

我试图建立一个PHP类:PHP - 从同一类中的另一个类变量设置类变量?

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]; 

返回同样的错误:

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

但是访问功能中的变量是细:

private $otherVar; 

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

如何使用先前定义的类变量定义和初始化当前一个,而无需额外的功能?

+2

使用最后一个代码块,它必须能够在编译时进行评估,不能依赖于运行时,正确的方法http://de2.php.net/manual/ zh/language.oop5.properties.php – Ghost

+1

在构造函数中分配。 – shudder

+0

够好,谢谢大家。 – Birrel

回答

3

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

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