Constant vs properties in php?

I just do not understand,

class MyClass { const constant = 'constant value'; function showConstant() { echo self::constant . "\n"; } } class MyClass { public $constant = 'constant value'; function showConstant() { echo $this->constant . "\n"; } } 

What is the main difference? This is exactly the same as defining var, isn't it?

+4
source share
3 answers

Constants are constant (wow, who would have thought of this?) They do not require an instance of the class. So you can write MyClass::CONSTANT , for example. PDO::FETCH_ASSOC . A property, on the other hand, needs a class, so you need to write $obj = new MyClass; $obj->constant $obj = new MyClass; $obj->constant .

In addition, there are static properties; they do not need an instance ( MyClass::$constant ). And here the difference is that MyClass::$constant can be changed, but MyClass::CONSTANT may not be.)

So, use a constant whenever you have a scalar value without an expression that will not be changed. This is faster than a property, it does not pollute the property namespace, and it is more understandable to anyone reading your code.

+7
source

By defining a const value inside a class, you will ensure that it will not be changed intentionally or unintentionally.

+2
source

Well, if I do $myClass->constant = "some other value" (given that $ myClass is an instance of MyClass) in the last example, then the value is no longer constant. There you have a difference. The value of a constant cannot be changed, because ... it is constant.

-1
source

All Articles