The Street Way

Access Control Modifiers

Access Control Modifiers


There are a number of keywords you can place before a class, a method definition, or a property to alter the way PHP treats them. Here's the full list, along with what each of them does:

  • Public: This property or method can be used from anywhere in the script.
  •  Private: This property or method can be used only by the class or object it is part of; it cannot be   accessed elsewhere.
  • Protected: This property or method can be used only by code in the class it is part of, or by   descendants of that class.
  •  Final: This property, method, or class cannot be overridden in subclasses.
  • Abstract: This method or class cannot be used directlyyou have to subclass this.

The problem with public properties is that they allow methods to be called and properties to be set from anywhere within your script, which is generally not a smart thing. One of the benefits of properly programmed OOP code is encapsulation, which can be thought of as similar to data hiding. That is, if your object exposes all its properties to the world, programmers using those objects need to understand how your classes work. In an encapsulated word, other programmers would only need to know the specification for your class, such as "call function X, and you'll get Y" back. They wouldn't and shouldn't have to know how it all works internally.




To give an example of this, we had a ATag object $ATag inside each A object, as well as a $Name property, but they contained repeated information. If someone had changed the $Name property, the $ATag information would have remained the same. The programmer can't really be blamed for changing $Name: it was publicly accessible, after all. The solution is to make all the variables private to the object using either private or protected, and to provide accessor methods like setName( ) to stop unknowing programmers from changing variables directly. These accessors are written by us, so we can have them do all the necessary work, such as changing the name on the dog tag when a dog's name changes.

Generally speaking, most of the variables in a class should be marked as either protected or private . Sometimes you will need to use public , but those times are few and far between.

0 comments:

Post a Comment