views:

36

answers:

2

I found out that object constants in PHP always have public visibility so it is not possible to set them to protected or private like this:

<?php
class MyClass {
    protected const constant = "this won't work";
}
?>

What's the explanation for this? I can't think of a good reason to force constants to be public.

A: 

I can't think of a good reason to force constants to be public.

Well, constants are static definitions, bound to the class and not instantiated objects. They can be addressed only using classname::constname, and they cannot be altered. It stands to reason they are part of the blueprint of a class, and thus it doesn't really make sense to apply visibility rules to them.

That's just my rather subjective opinion, though. Interested to see whether anything based on hard OOP theory comes up.

Pekka
Hmm, shouldnt static class members be always public by that definition, too?
Gordon
@Gordon hmm, true.
Pekka
+2  A: 

That's a rather philosophical question, which is discussed in the comments for Class constants in the PHP Manual. The argument seems to be that Visibility identifies who has the right to change members, not who has the right to read them. Since constants cannot be changed, there is no point in having them support visibility when visibility is understood as access modifiers. If you follow that argumentation or go with the linked feature request below your question is up to you.

Gordon
I don't follow the argument at all, but good link!
Pekka
@Pekka yeah, I am undecided on which to follow. I can see uses for constants having visibility but then again, it's nothing I ever felt strongly about. Constants are constants and if I need visibility I use properties.
Gordon
@Gordon yeah, I too think it's not a big deal either way (although it's interesting). But the argument that "visibility controls the right to *write* " doesn't make sense to me at all. That sounds plain wrong to me.
Pekka