【问题标题】:PHP Constants in Classes类中的 PHP 常量
【发布时间】:2011-05-23 02:20:55
【问题描述】:

我有以下代码示例,它在运行时会产生包含常量的错误。有人可以告诉我这是哪里出错了吗?

class Template {
  private $headers = "<link rel=\"stylesheet\" type=\"text/css\" 
  href=\"" . ROOT . "system/stylesheets/universal.css\" />";

  ... More variables and methods
}

这是我收到的错误。我确信 ROOT 常量是在这个类之外定义的:

Parse error: syntax error, unexpected '.', expecting ',' or ';' in <page.php> on line <line number>

感谢您的宝贵时间,
spryno724

【问题讨论】:

    标签: php oop class constants


    【解决方案1】:

    您不能将非静态值指定为您的成员默认值。而且您正在尝试执行动态(运行时)的事情 - 字符串的串联。

    class Template
    {
        public static headers()
        {
            return '<link rel="stylesheet" type="text/css" href="' . ROOT . 'system/stylesheets/universal.css" />';
        }
    }
    

    用法:

    $headers = Template::headers()
    

    另外 - 我错过了您只使用实例变量,而不是常量。在这种情况下,您还可以在构造函数中使用初始化:

    class Template
    {
        private $headers;
    
        public static __construct()
        {
            $this->headers = '<link rel="stylesheet" type="text/css" href="' . ROOT . 'system/stylesheets/universal.css" />';
        }
    }
    

    【讨论】:

    • @spryno724: 静态类方法?
    • 大声笑,我要推荐的完全重复的解决方案,我正在删除我的帖子,因为你已经发布了答案。
    • +2 很好的例子,很好的答案,...我希望我能做一个 +2
    猜你喜欢
    • 2010-10-15
    • 1970-01-01
    • 2011-04-25
    • 1970-01-01
    • 2011-08-19
    • 1970-01-01
    • 1970-01-01
    • 2012-05-09
    • 2020-12-20
    相关资源
    最近更新 更多