Saturday, October 13, 2012

PHP Access Specifiers

There are three access specifiers in PHP: public, private, and protected.

Public

The access specifier public allows properties of a class to be accessed/modified outside the class without having to go through a get or set method. This allows for the least amount of protection for the property.

class Person {
 public $name;
 
 public function setName($name) {
  $this->name = $name;
 }
 
 public function getName() {
  return $this->name;
 }
}
 
$p = new Person();
$p->setName("Bob Jones");
echo $p->name;  // echos Bob Jones no error because it is public
$p->name = "Joe Smith" ; // this sets the name to Joe Smith only because it is public

Private

Private is another access specifier that offers the most protection for a property. The property is only editable within the class itself.

class Person {
 private $name;
 
 public function setName($name) {
  $this->name = $name;
 }
 
 public function getName() {
  return $this->name;
 }
}
 
$p = new Person();
$p->setName("Bob Jones");
echo $p->getName(); //this will echo Bob Jones
echo $p->name; //can't access name this way, only through getName()
$p->name = "Joe Smith" ; //can't set name this way either         

Protected

The protected access specifier offers more protection then public but allows for a property to be accessed in its class and all other classes that extend its class.

class Person {
 protected $name;
 
 public function setName($name) {
  $this->name = $name;
 }
 
 public function getName() {
  return $this->name;
 }
}
 
class Employee extends Person {
 
 private $employeeNumber;
 
 public function setEmployee($name, $employeeNumber) {
  $this->name = $name; //this is storing name in the person class 
  $this->employeeNumber = $employeeNumber;
 }
        
}
 
$e = new Employee();
$e->setEmployee("Bob Jone",10000100);
echo $e->name; // this would throw an error as it is only accessable through methods in Employee or Person class

No comments:

Post a Comment