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?

My answer:


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!

This entry was posted on Thursday, December 6th, 2007 at 1:08 pm and is filed under Object Oriented PHP. You can follow any responses to this entry through the RSS 2.0 feed. Both comments and pings are currently closed.

3 Responses to “A Question about object properties in PHP Classes.”

  1. 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.

  2. Stefan Mischook says:


    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:




  3. Stefan Mischook’s Blog: A Question about object properties in PHP Classes…

    Stefan Mischook shares a little question and answer he had recently ……

Created By Stefan Mischook  |  Top of page  go to top of page