News & UpdatesProgrammingWeb programming StoreMy Projects
Links
Affiliates

PHP Tutorial – 12 – Access Levels

Every class member has an accessibility level that determines where the member will be visible. There are three of them available in PHP: public, protected and private.

class MyClass
{
  public    $myPublic;    // unrestricted access
  protected $myProtected; // enclosing or child class
  private   $myPrivate;   // enclosing class only
}

Private access

All members regardless of access level are accessible in the class in which they are declared, the enclosing class. This is the only place where a private member can be accessed.

class MyClass
{
  public    $myPublic    = 'public';
  protected $myProtected = 'protected';
  private   $myPrivate   = 'private';
 
  function test()
  {
    echo $this->myPublic;    // allowed
    echo $this->myProtected; // allowed
    echo $this->myPrivate;   // allowed
  }  
}

Unlike properties, methods do not have to have an explicit access level specified. They will default to public access unless set to another level.

Protected access

A protected member can be accessed from inside of child or parent classes as well as from within the enclosing class.

class MyChild extends MyClass
{
  function test()
  {
    echo $this->myPublic;    // allowed
    echo $this->myProtected; // allowed
    echo $this->myPrivate;   // inaccessible	
  }  
}

Public access

Public members have unrestricted access. In addition to anywhere a protected member can be accessed, a public member can also be reached through an object variable.

$m = new MyClass();
echo $m->myPublic;    // allowed	
echo $m->myProtected; // inaccessible	
echo $m->myPrivate;   // inaccessible

Var keyword

Before PHP 5 the var keyword was used to declare properties. In order to maintain backward compatibility this keyword is still usable and gives public access just as the public modifier.

class MyVars
{
  var $x, $y; // deprecated property declaration
}

Object access

In PHP, objects of the same class have access to each other’s private and protected members. This behavior is different from many other programming languages where such access is not allowed.

class MyClass
{
  private $myPrivate;
 
  function setPrivate($obj, $val) {    
    $obj->myPrivate = $val; // set private property
  }
}
 
$a = new MyClass();
$b = new MyClass();
$a->setPrivate($b, 10);

Access level guideline

As a guideline, when choosing an access level it is generally best to use the most restrictive level possible. This is because the more places a member can be accessed the more places it can be accessed incorrectly, which makes the code harder to debug. Using restrictive access levels will also make it easier to modify the class without breaking the code for any other developers using that class.

Recommended additional reading:
Sams - Teach Yourself PHP in 24 Hours