PUBLIC, PRIVATE & PROTECTED IN PHP 5

INTRODUCTION:

Public, Private and Protected 
are access identifiers that allow you to specify what level of access other code has to certain variables and methods within an individual class.

Some data you may want to keep within a class and other data available to a whole program – Public, Private and Protected identifiers allow us to control the scope of our data.

THE PUBLIC IDENTIFIER:
When using the pubic identifier you are allowing access to a classes attributes and methods from outside the class e.g. :
<?php
  class WebDeveloper {
    public $name;
    public function __construct($name) {
      $this->name = $name
    }
  }
?>
You can see the public identifier stated before the attributes and before the method. The following code would allow you to access the attributes:

<?php
  $developer = new WebDeveloper('sam');
  echo $developer->name;
?>

THE PRIVATE IDENTIFIER:
When using the private identifier you are not allowing access to a classes attributes and methods from outside the class e.g. :
<?php
  class WebDeveloper {
    private $name;
    private function __construct($name) {
      $this->name = $name
    }
  }

?>
You can see the private identifier stated before the attributes and before the method. Trying to access the private variables like this:


<?php
  $developer = new WebDeveloper('sam');
  echo $developer->name;
?>
would throw and error because the attribute is set to private. To access the attributes the class would have to have a public method that can return the value:


<?php
class WebDeveloper {
  private $name;
  private function __construct($name) {
    $this->name = $name
  }
  public function getName() {
    return $this->name;
  }

}?>
As you can see there is now an extra method that is public therefore this can be used to return the value because its within the correct scope:
<?php
  $developer = new WebDeveloper('sam');
  echo $developer->getName();
?>
THE PROTECTED IDENTIFIER:
Now the protected identifier is used when dealing with inheritance. An attribute that is given a protected scope can only be accessed within the class and to any other classes that extend the base class. For example take our base class:
<?php
  class WebDeveloper {
    private $name;
    private function __construct($name) {
      $this->name = $name
    }
    public function getName() {
      return $this->name;
    }
  }
?>
If you tried to access the ‘name’ after instantiating the Web_Developer object like below:


<?php
  $developer = new WebDeveloper('sam');
  echo $developer->name;
?>
You would get an error because the attribute is not accessible from outside the class. But using the public method like so:


<?php
  $developer = new WebDeveloper('sam');
  echo $developer->getName();
?>
is ok, the main difference between protected and private class properties is that protected properties can also be accessed by extended classes.


Comments