PHP OOP - Access Modifiers
In PHP Object-Oriented Programming (OOP), access modifiers are keywords that control the visibility of class members (properties and methods).
There are three main access modifiers in PHP:
- public
- protected
- and private .
Public:
When a property or method is declared as public, it means it can be accessed from outside the class, as well as from within the class and its subclasses.
Example
<!DOCTYPE html> class MyClass { public $publicProperty; public function publicMethod() { echo "This is a public method."; } } $obj = new MyClass(); echo $obj->publicProperty; // Accessing public property $obj->publicMethod(); // Accessing public methodYou can click on above box to edit the code and run again.
Output
Protected:
When a property or method is declared as protected, it means it can only be accessed from within the class and its subclasses, but not from outside the class.
Example
<!DOCTYPE html>
class MyClass {
protected $protectedProperty;
protected function protectedMethod() {
echo "This is a protected method.";
}
}
$obj = new MyClass();
//echo $obj->protectedProperty; // Cannot access protected property from outside
//$obj->protectedMethod(); // Cannot access protected method from outside
You can click on above box to edit the code and run again.Output
Private:
When a property or method is declared as private, it means it can only be accessed from within the class itself, but not from its subclasses or outside the class.
Example
<!DOCTYPE html>
class MyClass {
private $privateProperty;
private function privateMethod() {
echo "This is a private method.";
}
}
$obj = new MyClass();
//echo $obj->privateProperty; // Cannot access private property from outside
//$obj->privateMethod(); // Cannot access private method from outside
You can click on above box to edit the code and run again.Output
public: Accessible from anywhere.
protected: Accessible from the class itself and its subclasses.
private: Accessible only from the class itself.