PHP Access Modifiers
The use of access modifiers in PHP determines which parts of a class are visible and accessible from different contexts such as within the class itself or from child classes or external code.
Types of Access Modifiers in PHP
Modifier | Visibility |
---|---|
public | Accessible from anywhere (inside, outside, or subclasses) |
protected | Accessible inside the class and in subclasses |
private | Accessible only within the class where it's defined |
Example: All Three Modifiers
<?php class Demo { public $publicVar = "Public"; protected $protectedVar = "Protected"; private $privateVar = "Private"; public function showVars() { echo "Inside class:<br>"; echo $this->publicVar . "<br>"; echo $this->protectedVar . "<br>"; echo $this->privateVar . "<br>"; } } $obj = new Demo(); $obj->showVars(); echo "<hr>Outside class:<br>"; echo $obj->publicVar . "<br>"; // Accessible // echo $obj->protectedVar; // Error // echo $obj->privateVar; // Error ?>
Access Level | Inside Class | Subclass | Outside Class |
---|---|---|---|
public | ✅ | ✅ | ✅ |
protected | ✅ | ✅ | ❌ |
private | ✅ | ❌ | ❌ |
Quickly Find What You Are Looking For
OnlineTpoint is a website that is meant to offer basic knowledge, practice and learning materials. Though all the examples have been tested and verified, we cannot ensure the correctness or completeness of all the information on our website. All contents published on this website are subject to copyright and are owned by OnlineTpoint. By using this website, you agree that you have read and understood our Terms of Use, Cookie Policy and Privacy Policy.