How can I concatenate a constant and a variable and store it in a class constant using PHP?

  class My_class
 {
     const STATUS_ERROR = 0;
     const STATUS_OK = 1;
     const DB_TABLE = TABLE_PREFIX.  'class_table';
 } 

The two states of consts work fine and can be accessed in class methods, because self::STATUS_ERROR and self::STATUS_OK just fine.

The problem is how to stop the next error that occurs when trying to determine the third constant.

Parse error: syntax error, unexpected '.', expecting ',' or ';' in /home/sub/sub/directory/script.php

+6
oop php class const constants
source share
2 answers

Not. The constants are constant. You cannot store anything in them.

However, you can use a static property.

 class My_Class { public static $DB_TABLE; } My_Class::$DB_TABLE = TABLE_PREFIX . 'class_table'; 

You cannot do this in a declaration, so you may prefer a static method instead.

 class My_Class { public static function dbTable() { return TABLE_PREFIX . 'class_table'; } } 
+9
source share

a const must be defined with a constant value, they cannot be the result of the expression

http://www.phpbuilder.com/manual/en/language.oop5.constants.php

+3
source share

All Articles