Access modifiers determine the visibility of properties and methods within your classes. With them, we precisely control which parts of the code can see, read, or modify the data inside an object. This is a fundamental concept of object-oriented programming called encapsulation (data hiding), which prevents external code from accidentally or unauthorizedly altering critical system data.
PHP offers three main access modifiers, which we write right before the definition of a variable or method:
| Modifier | Visibility and Accessibility |
|---|---|
public |
Accessible to everyone: Properties and methods are visible from anywhere – inside the class, in subclasses, and in external code. |
protected |
Accessible to the family (Inheritance): Visible only within the same class and in all subclasses that inherit from it (extends). External code has no access. |
private |
Strictly private: Visible exclusively within the class where it is defined. Subclasses (children) cannot see or modify this data. |
If we map the levels of visibility to everyday life, you can imagine them as spaces in your house: