views:

46

answers:

3
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

+6  A: 

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.

Raoul Duke
C++ and Java allow you to access static members through instance expressions, but Jon Skeet gives an example of why it might be confusing to do that: http://stackoverflow.com/questions/163026/what-is-your-least-favorite-syntax-gotcha/163181#163181 - so best not to even if you can.
Michael Burr
Yes I wouldn't recommend it. Thanks for the link.
Raoul Duke
+2  A: 

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 ::.

Alin Purcaru
+1 Good pickup on the OP missing the extra :
Blair McMillan
+1  A: 

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.

Russell Dias