What is the difference between public, protected, and private in PHP?
Why Interviewers Ask This
Foundational questions like this help interviewers calibrate the rest of the interview. A confident, accurate answer signals that you have solid PHP basics — a prerequisite for any developer role.
Answer
PHP has three access modifiers for class properties and methods. public: accessible from anywhere — inside the class, subclasses, and external code. protected: accessible only within the class itself and by subclasses (child classes). Not accessible from outside the class hierarchy. private: accessible only within the class where it is defined. Subclasses cannot access private members. Best practice: make all properties private or protected and expose them through public getters/setters to maintain encapsulation. PHP 8.1 added readonly properties (can be set only once, in the constructor), and PHP 8.2 added asymmetric visibility modifiers.
Pro Tip
Before answering, structure your response: one-line definition → real-world analogy → concrete example from a project. This makes even complex PHP answers easy to follow.