Class visibility vs. security


#1

I’m planning on using PHP to Process Hypertext on a web server. Is there any benefit from declaring classes and variables as anything other than public, or, in other words, is there any inherent security risk in simply allowing everything to be public?


#2

In PHP I don’t think it could do much harm, as it’s an interpreted language and when someone else uses it, it’s hard to hide class members because this someone else could easily change the class code :slight_smile:

Compiled languages such as Java or C# however do not give away the source code. For the sake of such languages, and consistency, it is always a best-practice to give a class member the smallest visibility possible. This may be one of the following:

  • private (for class-only members)
  • protected (for class and subclass (and in PHP superclass) scope)
  • no access modifier (in Java this means package scope, I don’t think PHP supports this)
  • public (random access - cannot guarantee the value … or the type of the variable).

These only go for class members though (so class-wide variables and methods), and not for variables defined and used only inside a method.