PHP Access Modifiers: Types of Specifiers, How to Use with Examples

PHP Access Modifiers are used to define the range of the Class Property or Variable. Using Access modifiers we define where we can use that particular variable.

What are Access Modifiers in PHP?

Access Modifiers are used to control where we access Properties and Methods.

Access modifiers are an important part of PHP code since they allow us to make our code more secure.

Suggested: PHP Constructor and Destructor

Types of PHP Access Modifiers

There are three types of access modifiers available in PHP – Public, Private and Protected.

Each of them defines where we can access that particular Property or Method.

To define the access we don’t have to do much just write either Public, Private, or Protected before the name.

Here is what these three access modifiers do:

  • public – The Property or Method that we set public can be accessed from anywhere. If we want to set something public, we don’t even have to write this keyword. By default, every method and property is public unless specified otherwise.
  • private – Private, well set a property or method private this means these can only access from within the class.
  • protected – This set method or property protected, which means it can be only accessed from class and other classes derived from that one class.

Public, Private & Protected in PHP examples

Here is how we can use Public, Private, and Protected access specifiers to set properties access-

class Student {
    public $name;
    protected $id;
    private $result;
}

So following this code we can access property $name within or outside class.

id can be accessed from the Student class and other classes that inherit from it.

The final property $result can access only from the Student class and from no other place.

Similar to property we can use access modifiers for methods as well:

class Student {
    public $name;
    protected $id;
    private $result;
    
    function set_name($n) {  // a public function (default)
    $this->name = $n;
  }
    
  protected function set_id($n) { // a protected function
    $this->id = $n;
  }
  private function set_result($n) { // a private function
    $this->result = $n;
  }
}

About Rahul Bodana

Rahul Bodana is passionate about sharing his knowledge with others and providing useful tutorials and how-to guides. In addition to programming, he also shares information on a variety of topics, including investment, trading, gaming, and writing.