PHP Class Constants - Public, Private or Protected?

前端 未结 4 935
余生分开走
余生分开走 2020-12-09 14:43

Am I correct in assuming that const properties are automatically public? Is there a way to make them private or protected?

Thanks in advance.

4条回答
  •  眼角桃花
    2020-12-09 15:19

    Class constants should have the option of being private/protected because being public exposes internal details of the class that other classes/code can mistakingly use thinking they are ok to use because they are public.

    It would be nice to know that changing a private constant would ONLY affect the class it's defined in. Unfortunately we don't have that option.

    Remember back to when you were learning Object Design & Analysis... you give class methods and attributes the most RESTRICTIVE access possible, and later relax them as needed (much harder to go back the other way because other classes/code start using them which would then break other code).

    WORKAROUND

    Best bet is to just create a private or protected variable and upper-case it to show it's a constant. You could always create a class called constant($value_to_be_constant) that implements the correct magic methods / spl interfaces to prevent it from being changed.

提交回复
热议问题