就像c++一样,可以在构造函数中初始化类常数吗?
类似于c++,它看起来像:
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?
}
}
不,这在PHP中是不可能的。定义常量时必须定义常量的值,且必须是常量表达式。
不推荐:当然,如果安装了runkit,也可以使用runkit_constant_add()
:
public function __construct($width)
{
runkit_constant_add(__CLASS__ . '::WIDTH', $width);
}