![](/img/trans.png)
[英]Can I access a PHP Class Constant using a variable for the constant name?
[英]How can I concatenate a constant and a variable and store it in a class constant with PHP?
class My_class { const STATUS_ERROR = 0; const STATUS_OK = 1; const DB_TABLE = TABLE_PREFIX . 'class_table'; }
兩個狀態consts工作正常,可以在類方法中訪問self::STATUS_ERROR
和self::STATUS_OK
就好了。
問題是當我嘗試定義第三個常量時如何停止拋出以下錯誤。
Parse error: syntax error, unexpected '.', expecting ',' or ';' in /home/sub/sub/directory/script.php
你沒有。 常數是不變的。 你不能存儲任何東西。
您可以使用靜態屬性。
class My_Class {
public static $DB_TABLE;
}
My_Class::$DB_TABLE = TABLE_PREFIX . 'class_table';
您無法在聲明中執行此操作,因此您可能更喜歡靜態方法。
class My_Class {
public static function dbTable() {
return TABLE_PREFIX . 'class_table';
}
}
const必須用常量值定義,它們不能是表達式的結果
http://www.phpbuilder.com/manual/en/language.oop5.constants.php
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.