Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Visibility of object constants

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.

like image 795
Nick Avatar asked Aug 18 '10 09:08

Nick


2 Answers

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.

like image 66
Gordon Avatar answered Nov 15 '22 14:11

Gordon


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.

like image 1
Pekka Avatar answered Nov 15 '22 14:11

Pekka