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, that MyClass::$constant
may be changed, but MyClass::CONSTANT
may 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.
By defining a const
value inside a class, you make sure it won't be changed intentionally or unintentionally.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With