Back to results for “OOP & Classes”
PHP › OOP

What are the three visibility modifiers in PHP, public, protected, and private, and how do they control access to a class's properties and methods?

Beginner

Answer

The public modifier allows a property or method to be accessed from anywhere, including outside the class entirely, protected restricts access to the class itself and any classes that extend it, and private restricts access exclusively to the exact class where it is defined, not even allowing access from a subclass, and choosing the appropriate visibility for each member is an important part of properly encapsulating a class's internal implementation details.
class BankAccount {
    private $balance;
    protected $accountType;
    public $accountNumber;
}
Real-world example A BankAccount class marks its balance property as private to prevent any external code from directly modifying it without going through proper validated methods, while marking accountNumber as public since it is safe and expected to be freely read by other parts of the application.

Common follow-ups: Why might a property be marked protected rather than private if a subclass needs access to it?;What happens if you try to access a private property from outside its defining class?