PHP 5: Public, private, protected

PHP 5 allows you to declare properties and methods as public, private or protected. These are defined as:

  • Public: anyone either inside the class or outside can access them
  • Private: only the specified class can access them. Even subclasses will be denied access.
  • Protected: only the specified class and subclasses can access them

It is good practice to mark properties as protected (at least) and to use get/set methods to change their value. This future-proofs the code and can reduce the number of changes that need to be made. E.g. the existing user code makes use of an isLoggedIn variable. Making the variable protected and adding a method to set its value like this:

class User
{
 protected $isLoggedIn = false;

 function User()
 {
 }

 function setLogin($loginValue)
 {
  $this->isLoggedIn = $loginValue;
 }

}

will prevent code outside of the class (or subclasses) from changing the value of isLoggedIn without going through the setLogin() method. Although it may seem long-winded, the code of User may change in the future e.g. with the addition of a ‘LogState’ object to handle the logging in status:

class LogState
{
 protected $isLoggedIn = false;

 function __construct()
 {
 }

 function setLogin($isLoggedIn)
 {
  $this->isLoggedIn = $isLoggedIn;
 }
}

class User
{
 protected $logState;

 public function User()
 {
  $this->logState = new LogState()
 }

 public function setLogin($loginValue)
 {
  $this->logState->setLogin(true);
 }

}

If access to the logged in state of the user is protected then every change to it will be through the setLogin method. Now that a new object is controlling the state, only the method needs to change and no other code will notice the alteration.
Protected and private methods prevent outside calls to methods which may upset the internal state of an object.

Next section: Abstract classes

Advertisements
This entry was posted in PHP, Programming. Bookmark the permalink.

5 Responses to PHP 5: Public, private, protected

  1. brudinie says:

    Nice succinct explanation of what PHP5 private and protected variables are and how they work. Just what I needed, thanks.

  2. Anonymous says:

    Agreed. Excellent explanation. I know it’s been 4 years but it still helps us newbies!

  3. fatjoe says:

    great examplethanks

  4. Anonymous says:

    Great little tutorial, as it also explains how you can chain methods in PHP5.

  5. Zlatan says:

    Good stuff!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s