2016-10-06 201 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