A Question about object properties in PHP Classes.
I got this question put to me recently:
Since you say it’s bad practice to access object properties directly from outside the class, is it then good practice to declare all variables as protected or private to force yourself to not?
Many OO techniques are designed for situations where you will have more than one programmer involved, now or later. By declaring variables as protected or private, you are adding security to the code base by forcing the use of getter and setter methods where you can control how objects are used.
The thing is that with PHP, since the code is not compiled a programmer could just pop open the script and make changes. Whereas with compiled languages like Java, the users of your class have no choice.
… Unless they decompile the class!
Designing applications with interfaces also helps. Essentially, you specify the implementation of the class in a separate file that is implemented in your concrete class. Interfaces work really well in C# / Java due to the strong-typed nature of the language, however that doesn’t mean that PHP developers should be sloppy. If anything, we should be more rigorous in our development practices.
Jon is correct and I actually prefer using interfaces to set standards in the code base over abstract or concrete classes … more flexible.
If any of you are not sure what interfaces are: