constant vs properties in php?
I just don't get it,
class MyClass
{
const constant = 'constan开发者_高级运维t 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.
Well, if I do $myClass->constant = "some other value"
(given $myClass is an instance of MyClass) in the latter example, then the value is no longer constant. There you have the difference. The value of a constant can not be changed, because... it is constant.
精彩评论