class foo
{
const bar;
}
and to access it we have to do: self:bar; and not, $this->bar;
Is this correct?
If so, why?
Thanks a lot, MEM
class foo
{
const bar;
}
and to access it we have to do: self:bar; and not, $this->bar;
Is this correct?
If so, why?
Thanks a lot, MEM
Yes this is correct. The reason is that a constant is class-bound whereas a property is instance-bound so it wouldn't make much sense to access it through a reference. No matter how many instances you create there will always only be one foo::bar const.
It's just a language design decision that it's not possible to access a const through a reference though, in Java for example you can indeed access a static final property through a reference but you will usually get a compiler warning.
Well, because they are constants that means they are static (constant and static are synonyms) and also it makes no sense in having one for each instance if they don't ever change, so you have them per class. Static members are accessed with ::
.
A good point to note, which has been missed thus far is the fact that constants can contain only primitive values. They also cannot be changed once they are set, an attempt to set a value after its already declared will result in a parse error
.
You should essentially use constants only when your property is needed across every instance of the class, and of course if it needs to be fixed.