Access Modifiers
Access Modifiers
In the PHP programming language, every property and method of a class can have access modifiers which control their accessibility in the entire program.
There are three access modifiers in PHP:
- Public
- Protected
- Private
Below is a table for a better understanding of the access modifiers
Class Member 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 |
Public
Public property or method can be accessed by any code whether that code is inside or outside of that class. If a property or method is declared public, then it can be accessed anywhere from the code.
Example:
Protected
Protected property or method can only be accessed within the class and by the classes derived from that class.
Example:
Output:
Private
The Private property or method can only be accessed within the class. If it is called outside of the class, then it will throw an error.
Example: