Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.


  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • DownloadDownload
  • PrintPrint
Share this Page URL
Help

Chapter 6. Objects > Public, Protected, and Private

6.5. Public, Protected, and Private

Just as you can set scope in procedural PHP, you can also set it in the OOP aspect of PHP. You can identify your properties and your methods as either public, protected, or private. An entity with public scope is open to use and access outside the class definition itself. An entity with protected scope is only accessible within the class in which it is defined and its parent or inherited classes. Finally, an entity with private scope is only accessible within the class that defines it.

Encapsulation, the concept of protecting entities within a class from any outside influences, can best be achieved using the private scope attribute. A little later in this chapter, we will look at a person class to see this in action. Basically, it is always best to limit the scope access of a class from outside influences, especially if you are writing a class library that will be used in many different projects or if you are making a commercially available library. This protects your code from being tripped up in any way, either by improper use or by directly accessing its properties from outside the class itself. The protected scope is rarely used unless you have a heredity tree (inherited classes) that can benefit in some way. The public scope is the default scope if none is declared, and it is used best on methods that allow the class to interface with the outside world. The best way to share information to an outside entity that is making use of your class is with the public get and set methods (a.k.a. accessor methods) that act on the privately declared class properties. We’ll look at this more closely in the following section.


  

You are currently reading a PREVIEW of this book.

                                                                                        

Get instant access to over
$1 million worth of books and videos.

  

Start a Free Trial