PHP Access Modfiers
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.
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.
At Online Learner, we're on a mission to ignite a passion for learning and empower individuals to reach their full potential. Founded by a team of dedicated educators and industry experts, our platform is designed to provide accessible and engaging educational resources for learners of all ages and backgrounds.
Copyright 2023-2025 © All rights reserved.