🐘 PHP Beginner

What is the difference between public, protected, and private in PHP?

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.