【问题标题】:How can I concatenate a constant and a variable and store it in a class constant with PHP?如何连接常量和变量并将其存储在 PHP 的类常量中?
【发布时间】:2010-02-10 10:27:29
【问题描述】:
类 My_class
{
    常量状态错误 = 0;
    常量状态确定 = 1;
    常量 DB_TABLE = TABLE_PREFIX 。 'class_table';
}

这两个状态常量工作正常,可以在类方法中访问self::STATUS_ERRORself::STATUS_OK 就好了。

问题是当我尝试定义第三个常量时如何停止引发以下错误。

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

【问题讨论】:

标签: php class oop constants


【解决方案1】:

你没有。常数是常数。您不能在其中存储任何内容。

您可以使用静态属性。

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

【讨论】:

    【解决方案2】:

    const 必须用常量值定义,它们不能是表达式的结果

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-10-17
      • 1970-01-01
      • 2013-04-06
      • 1970-01-01
      • 2020-12-20
      • 2015-08-16
      • 1970-01-01
      • 2017-04-20
      相关资源
      最近更新 更多