Access modifiers in PHP are used to determine where the members (methods or properties) of a class can be accessed from. They are a foundational concept in object-oriented programming.
There are three main access modifiers in PHP:
Let's look at each of these in detail with examples:
public
Properties or methods declared as public can be accessed from anywhere.
class Sample {
public $publicVar = "I am a public variable";
public function publicMethod() {
return "I am a public method";
}
}
$obj = new Sample();
echo $obj->publicVar; // Outputs: I am a public variable
echo $obj->publicMethod(); // Outputs: I am a public method
protected
Properties or methods declared as protected can only be accessed within the class itself and by inherited or child classes.
class Sample {
protected $protectedVar = "I am a protected variable";
protected function protectedMethod() {
return "I am a protected method";
}
}
class ChildSample extends Sample {
public function accessProtected() {
echo $this->protectedVar; // Accessible because it's a child class
echo $this->protectedMethod(); // Accessible because it's a child class
}
}
$obj = new ChildSample();
$obj->accessProtected(); // Outputs: I am a protected variableI am a protected method
private
Properties or methods declared as private can only be accessed from within the class itself.
class Sample {
private $privateVar = "I am a private variable";
private function privateMethod() {
return "I am a private method";
}
public function accessPrivate() {
echo $this->privateVar; // Accessible because it's within the same class
echo $this->privateMethod(); // Accessible because it's within the same class
}
}
$obj = new Sample();
$obj->accessPrivate(); // Outputs: I am a private variableI am a private method
When designing classes, it's good to think about which parts of your class should be exposed (public) and which parts should be hidden (protected or private). This encapsulation helps maintain data integrity and prevents unintended usage. Remember:
UPCET Exam
Click Here
SAAT Exam
Click Here
MHT CET Exam
Click Here
IPU CET Exam
Click Here
KCET Exam
Click Here
COMEDK UG Exam
Click Here
VITEEE Exam
Click Here
BITSAT
Click Here
DSAT: Dayanand Sagar Admission Test
Click Here
Career In Animation in india
Click Here
Merchant Navy Courses in india
Click Here
Interior Design Career in india
Click Here
UGC NET Exam
Click Here
B. Ed Exam
Click Here
AFCAT - Air Force Common Admission Test
Click Here
GATE Exam
Click Here
Joint Entrance Examination (JEE)
Click Here
Common Admission Test (CAT)
Click Here
CDS - Combined Defence Services Exam
Click Here