PHP Access Modifiers
In PHP, access modifiers define the visibility of properties and methods of a class. The three main access modifiers are:
- public
- protected
- private
Let's explore each of these with examples.
PHP Access Modifiers
Public
A property or method declared as public can be accessed from anywhere, both inside and outside the class.
class MyClass {
public $publicVar = "I am public";
public function publicMethod() {
return "This is a public method.";
}
}
$obj = new MyClass();
echo $obj->publicVar; // Output: I am public
echo $obj->publicMethod(); // Output: This is a public method.
Protected
A property or method declared as protected can only be accessed within the class itself and by inheriting classes.
class MyClass {
protected $protectedVar = "I am protected";
protected function protectedMethod() {
return "This is a protected method.";
}
}
class MyChildClass extends MyClass {
public function accessProtected() {
return $this->protectedVar . " " . $this->protectedMethod();
}
}
$obj = new MyChildClass();
echo $obj->accessProtected(); // Output: I am protected This is a protected method.
// The following will cause an error:
// echo $obj->protectedVar; // Fatal error: Uncaught Error: Cannot access protected property MyClass::$protectedVar
// echo $obj->protectedMethod(); // Fatal error: Uncaught Error: Call to protected method MyClass::protectedMethod()
Private
A property or method declared as private can only be accessed within the class itself. It is not accessible outside the class or by inheriting classes.
class MyClass {
private $privateVar = "I am private";
private function privateMethod() {
return "This is a private method.";
}
public function accessPrivate() {
return $this->privateVar . " " . $this->privateMethod();
}
}
$obj = new MyClass();
echo $obj->accessPrivate(); // Output: I am private This is a private method.
// The following will cause an error:
// echo $obj->privateVar; // Fatal error: Uncaught Error: Cannot access private property MyClass::$privateVar
// echo $obj->privateMethod(); // Fatal error: Uncaught Error: Call to private method MyClass::privateMethod()
Summary
- public: Accessible from anywhere.
- protected: Accessible within the class and by inheriting classes.
- private: Accessible only within the class itself.
These access modifiers help in encapsulating data and methods, providing control over the visibility and accessibility of class members.
Written by Shaikh Abdul Shahid
A Full-Stack Developer with experience in PHP, Laravel, JavaScript, and React.
Founder of Online Learner, sharing practical knowledge and programming tutorials.
Building and maintaining real-world web applications since 2017.
Your Feedback
Help us improve by sharing your thoughts
Online Learner helps developers master programming, database concepts, interview preparation, and real-world implementation through structured learning paths.
Quick Links
© 2023 - 2026 OnlineLearner.in | All Rights Reserved.
