![]() |
VOOZH | about |
In object-oriented programming, access specifiers are also known as access modifiers. These specifiers control how and where the properties or methods of a class can be accessed, either from inside the class, from a subclass, or from outside the class. PHP supports three primary access specifiers:
A public properties can be accessed from anywhere, from within the class, by inherited (child) classes, and from outside the class.. If a property is declared public, its value can be read or changed from anywhere in your script.
Now, let us understand with the help of the example:
GeeksforGeeks GeeksforGeeks
A private property or method is accessible only within the class that declares it. It is not accessible in child classes or from outside the class.
Now, let us understand with the help of the example:
Top Secret
Fatal error: Uncaught Error: Cannot access private property MyClass::$secret in /home/guest/sandbox/Solution.php:16
Stack trace:
#0 {main}
thrown in /home/guest/sandbox/Solution.php on li...A protected property or method can only be accessed within the class itself and by inheriting classes (subclasses). It is not accessible from outside the class.
Now, let us understand with the help of the example:
Output
Hello from Parent
Fatal error: Uncaught Error: Cannot access protected property ChildClass::$message in /home/guest/sandbox/Solution.php:18
Stack trace:
#0 {main}
thrown in /home/guest/sandbox/Solution.php on line 18In PHP, if no access specifier is provided for a property or method, the default access level is **`public`**. This means the property or method can be accessed from anywhere: within the class, from inherited classes, and from outside the class.
Output
GeeksforGeeks
GeeksforGeeks
In this example
| Access Specifier | Access from own class | Accessible from derived class | Accessible by Object |
| Private | Yes | No | No |
| Protected | Yes | Yes | No |
| Public | Yes | Yes | Yes |
Default (No Specifier) | Yes | Yes | Yes |
Access specifiers are foundational in PHP’s OOP model. Proper use of public, protected, and private helps build secure, and well-structured code. Choosing the right access level enforces better design practices and enhances code reusability and maintainability.