Access Modifiers in PHP Object-Oriented Programming define how and where class properties and methods can be accessed.
Access modifiers help implement encapsulation by restricting direct access to class data and enforcing controlled interaction through methods.
// Demonstrating public, protected, and private access modifiers
<?php
class Student {
public $name;
protected $rollNo;
private $marks;
public function __construct($name, $rollNo, $marks) {
$this->name = $name;
$this->rollNo = $rollNo;
$this->marks = $marks;
}
public function getMarks() {
return $this->marks;
}
}
$student = new Student("Rahul", 101, 95);
echo $student->name;
echo $student->getMarks();
?>
The name property is accessible directly because it is public. The marks property is private, so it can only be accessed using the getMarks() method.
Try changing access modifiers and observe how PHP throws errors when visibility rules are violated.
Use private for strict encapsulation, protected for inheritance, and public only when external access is required.
Create an Employee class with public, protected, and private properties and test accessibility using getter methods.