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?
}
}
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);
}