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