PHP Access Modifiers

PHP Access Modifiers


Access modifiers are used to control where properties and methods can be accessed.

There are three access modifiers :

  • public - From anywhere, a property or method can be accessed. As a result, this setting is the default.
  • protected - Within the class and by classes descended from it, the property or method can be accessed.
  • private - Only members of the class have access to the property or method.

Example 1 :- A simple program for different access modifier.

<?php
class Person {
  public $name;
  protected $gender;
  private $age;
}
$p1 = new Person();
$p1->name = 'Billgates'; // OK
$p1->gender = 'Male'; // ERROR
$p1->age = 55; // ERROR
?>

Try setting the name property and it will work (because the name property is public). But if you try to set the "gender" or "age" property, a fatal error will appear (because the gender and age property are protected and private) :




Example 2 :- Adding two public methods to access the private and protected properties.

<?php
class Person {
  public $name;
  protected $gender;
  private $age;
  public setGender($gender)
  {
    $this->gender = $gender;
  }
  public setAge($age)
  {
    $this->age = $age;
  }
}
$p1 = new Person();
$p1->name = 'Billgates';
$p1->setGender("Male");
$p1->setAge(55);
?>

Now, There will be a question on your mind? Why we have create public methods to access private members?

The answer is "To collect proper input data".

Example 3 :- Adding two public methods to access the private and protected properties.

<?php
class Person {
  public $age1;
  private $age2;
  function setAge2($age2)
  {
    if($age2 >= 18 && $age2 <= 60)
    {
        $this->age2 = $age2;
    }
  }
  function getAge2()
  {
    return $this->age2;
  }
}
$p1 = new Person();
$p1->age1=10000;
echo "Age 1 = " . $p1->age1 . "<br />";
$p1->setAge2(130);	//	It will not set
echo "Age 2 = " . $p1->getAge2() . "<br />";
$p1->setAge2(30);
echo "Age 2 = " . $p1->getAge2() . "<br />";
?>
Age 1 = 10000
Age 2 =
Age 2 = 30

The age1 property has invalid data because of direct access. But you cannot provide any invalid data on age2 property.

Note: You have a option to control your input data by using private modifier.



You can also search for these topics, access modifiers using php oop, php oop access modifiers Properties and methods, types of accesss modifiers in php oop, php oop public access modifiers, protected access modifiers using php oop, private property method in php oop access modifiers, Example for php oop access modifiers.