Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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';
}

The two status consts work fine and can be accessed within class methods as self::STATUS_ERROR and self::STATUS_OK just fine.

The issue is one of how to stop the following error being thrown when I try to define the third constant.

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

like image 674
Matthew Avatar asked Feb 10 '10 10:02

Matthew


2 Answers

You don't. Constants are constant. You can't store anything in them.

You can use a static property though.

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

You can't do it within the declaration, so you might prefer a static method instead.

class My_Class {
  public static function dbTable() {
    return TABLE_PREFIX . 'class_table';
  }
}
like image 113
troelskn Avatar answered Nov 08 '22 09:11

troelskn


a const must be defined with a constant value, they can't be the result of an expression

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

like image 39
Neil Aitken Avatar answered Nov 08 '22 09:11

Neil Aitken