Back to course

Access Modifiers: Public, Protected, and Private

PHP: The Complete 0 to Hero Bootcamp

35. Access Modifiers: Public, Protected, and Private

Access modifiers define the visibility and accessibility of class properties and methods. This is the cornerstone of Encapsulation.

1. public

Accessible from anywhere: inside the class, inside child classes, and from the outside (by an object instance).

php

balance; // Access from outside is OK ?>

2. protected

Accessible only from inside the class itself and from child classes that inherit it. Cannot be accessed directly from an object instance outside the class hierarchy.

3. private

Accessible only from inside the class itself where it is defined. Private members are invisible to both object instances and child classes.

Example Comparison

php

internal_id; // OK: Accessing private from inside } } $profile = new UserProfile(); echo "Name: " . $profile->name; // OK (Public) // echo $profile->role; // Fatal Error: Cannot access protected property // echo $profile->internal_id; // Fatal Error: Cannot access private property echo "
Internal ID via public method: " . $profile->showInternalId(); // OK ?>

Best Practice: Always default properties to private or protected. Expose them only through public methods (Getters and Setters) to control how data is read and written.