Access modifiers in class PHP, controls the accessibility(use) of its data members and member function. On this basis, a class in PHP has three access modifiers.

  1. public
  2. private
  3. protected
    publicThese properties or methods can be used inside and outside of class without restrictions
    privateThese properties or methods can only be used within or by class.
    protectedThese properties or methods can be used by class or its derived/child class.

    public Access modifiers

    class Student{
     public $marks;
    }
    
    $obj =  new Student();
    $obj->marks = 60;
    echo $obj->$marks;
    class Student{
     public $marks;
    
     function setMarks($m){
          $this->marks = $m;
     }
    }
    
    $obj =  new Student();
    $obj->setMarks(70);

    Private Access modifiers

    class Student{
     private $marks;
    }
    
    $obj =  new Student();
     // Error, because private members are not accessible outside class
    $obj->marks = 60;
    echo $obj->$marks;
    class Student{
     private $marks;
    
     private function setMarks($mr){
          $this->marks = $mr;
     }
    }
    
    $obj =  new Student();
    $obj->setMarks(90); // Error. Private members cannot be accessed.

    Protected Access modifiers

    class Student{
     protected $marks;
    }
    
    $obj =  new Student();
    $obj->marks = 60; // Error, because protected members are not accessible outside class
    echo $obj->$marks;
    
    class Student{
     protected $marks;
    
     protected function setMarks($mr){
          $this->marks = $mr;
     }
    }
    
    $obj =  new Student();
    $obj->setMarks(90); // Error. protected members cannot be accessed.