doujiekeyan0622
2011-12-20 17:56
浏览 165
已采纳

在PHP中的构造函数中初始化类常量

Just like in C++ is it possible to initialize class constant in the constructor?

Similar to C++ it'd look like:

class Abc
{
    const WIDTH;

    public __constructor($width):WIDTH($width) //WIDTH gets assigned here and is immutable
    {
        //I know syntax may not be ok but is anything similar possible in PHP?
    }

}

图片转代码服务由CSDN问答提供 功能建议

就像在C ++中一样,可以在构造函数中初始化类常量吗? < p>类似于C ++,它看起来像:

  class Abc 
 {
 const WIDTH; 
 
 public __constructor($ width):WIDTH($ width)  )// WIDTH在这里被赋值并且是不可变的
 {
 //我知道语法可能不行但在PHP中可能类似吗?
} 
 
} 
    
 
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dongxiane0395 2011-12-20 17:58
    已采纳

    No, this is not possible in PHP. A constant's value must be defined when you define the constant, and it must be a constant expression.

    Not recommended: Of course, if runkit is installed, you can use runkit_constant_add():

    public function __construct($width)
    {
        runkit_constant_add(__CLASS__ . '::WIDTH', $width);
    }
    
    已采纳该答案
    打赏 评论

相关推荐 更多相似问题