Tuesday, February 18, 2014

PHP - Access modifiers - 1


PHP - Access modifiers

 Access modifiers are used to access class members (variables and methods).

Acess modifiers are,

*  Public
*  Private
*  Protect

 Public variable and method can accessible from anywhere .

 Private members only accessible inside the class not the inherited class.

 In other terms private access control is used to maintain encapsulation functionality.

Protected members can only access from derived classes.


class Person
{
 public $name;
 protected $age;
 private $phone;
 
 function setName($name)
 {
  $this->name=$name;
 } 
 
 function getName()
 {
  return $this->name;
 }
 
 function setAge($age)
 {
  $this->age=$age;
 }
 

 function getAge()
 {
  return $this->age;
 }

 function setPhone($phone)
 {
  $this->phone=$phone;
 } 

 function getPhone()
 {
  return $this->phone;
 }


}

$person = new Person;



$person->setName('Sivanthi');
$person->setAge(28);
$person->setPhone('95******53');
echo $person->getName();  // output is  Sivanthi

echo $person->getAge();  // output is  28

echo $person->getPhone();  // output is  95******53

echo "Person Name is ".$person->name;  // output is Person Name is Sivanthi

echo "Person Age is ".$person->age; // Cannot access protected property Person::$age

echo "Person Phone is ".$person->phone; // Cannot access protected property Person::$phone


So we cannot directly access private and protected members from a class,

instead of we can use setters and getters to access those variables.


No comments:

Post a Comment