A Question about object properties in PHP Classes.

December 6, 2007

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:

Yes.

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!

3 Responses

  1. Jon Lebensold Author December 6, 2007 at 11:36 pm

    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 Author December 7, 2007 at 2:47 am

    Hi,

    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:

    http://www.killerphp.com/articles/php-interfaces/

    CIAO,

    Stefan

  3. Pingback: PHPDeveloper.org

To Top