2011-12-20 149 views
2

就像在C++中一樣,可以在構造函數中初始化類常量嗎?在構造函數中初始化類常量在PHP中

到C++類似它會看起來像:

class Abc 
{ 
    const WIDTH; 

    public __constructor($width):WIDTH($width) //WIDTH gets assigned here and is immutable 
    { 
     //I know syntax may not be ok but is anything similar possible in PHP? 
    } 

} 

回答

5

不,這是不可能的PHP。定義常量時必須定義一個常量值,並且它必須是一個常量表達式。

不推薦:當然,如果安裝runkit,您可以使用runkit_constant_add()

public function __construct($width) 
{ 
    runkit_constant_add(__CLASS__ . '::WIDTH', $width); 
} 
相關問題