I just don’t get it,
class MyClass
{
const constant = 'constant value';
function showConstant() {
echo self::constant . "\n";
}
}
class MyClass
{
public $constant = 'constant value';
function showConstant() {
echo $this->constant . "\n";
}
}
Whats the main difference? Its just same as defining vars, isn’t it?
Constants are constant (wow, who would have thought of this?) They do not require a class instance. Thus, you can write
MyClass::CONSTANT, e.g.PDO::FETCH_ASSOC. A property on the other hand needs a class, so you would need to write$obj = new MyClass; $obj->constant.Furthermore there are static properties, they don’t need an instance either (
MyClass::$constant). Here again the difference is, thatMyClass::$constantmay be changed, butMyClass::CONSTANTmay not.)So, use a constant whenever you have a scalar, non-expression value, that won’t be changed. It is faster than a property, it doesn’t pollute the property namespace and it is more understandable to anyone who reads your code.