2012-10-09 203 views
1

當我嘗試執行以下操作時,我得到一個syntax error, unexpected T_VARIABLE。我究竟做錯了什麼?在另一個屬性中訪問一個對象屬性

class myObj { 
    public $birth_month; 
    public $birthday = array('input_val' => $this->birth_month); 
} 

我也試過

class myObj { 
    public $birth_month; 
    public $birthday = array('input_val' => $birth_month); 
} 

回答

3

您不能使用表達式來初始化類屬性。它必須是一個常量值,或者你必須在構造函數中初始化它。這是你的語法錯誤的來源。

class myObj { 
    public $birth_month; 
    public $birthday; 

    // Initialize it in the constructor 
    public function __construct($birth_month) { 
    $this->birth_month = $birth_month; 
    $this->birthday = array('input_val' => $this->birth_month); 
    } 
} 

From the docs on class properties:

他們通過使用關鍵字公有,保護或私有,其次是普通變量聲明的一個定義。這個聲明可能包括一個初始化,但是這個初始化必須是一個常量值 - 也就是說,它必須能夠在編譯時進行評估,並且不能依賴運行時信息來進行評估。

在你的第一次嘗試,使用$this實例方法外不會被支持,即使霸菱屬性初始化的編譯時間的限制,因爲$this只是實例方法裏面有意義。

0

$這並不類的非靜態方法之外存在。另外,在初始化時,還沒有$。在構造函數方法中初始化您的數組。

相關問題