簡體   English   中英

PHP - 從同一個類中的另一個類變量設置類變量?

[英]PHP - Set class variable from another class variable within same class?

我正在嘗試建立一個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解析錯誤:語法錯誤,意外'$ tags'

將它切換到通常......

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

返回相同的錯誤:

PHP Parse錯誤:語法錯誤,意外'$ this'

但是訪問函數中的變量很好:

private $otherVar;

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

如何使用先前定義的類變量來定義和初始化當前變量,而無需額外的功能?

做你想做的最接近的方法是將賦值放在構造函數中。 例如:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM