O'Reilly logo

PHP in a Nutshell by Paul Hudson

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 directly—you 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 DogTag object $DogTag inside each dog object, as well as a $Name property, but they contained repeated information. If someone had changed the ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required