PHP Public vs Protected vs Private Visibility Modifiers
In PHP object-oriented programming, visibility modifiers (also known
as access modifiers) define where class properties and methods can be
accessed. This article provides a direct comparison of the three primary
visibility modifiers—public, protected, and
private—explaining their rules, inheritance behavior, and
practical use cases to help you write secure and well-structured
code.
Public Visibility
The public modifier is the least restrictive access
level in PHP.
- Scope: Public properties and methods can be accessed from anywhere—inside the class, by subclass instances (inheritance), and from external code outside the class.
- Default Behavior: If you declare a class method
without specifying a visibility modifier, PHP automatically treats it as
public. - Use Case: Use
publicfor methods and properties that need to be part of the class’s external API, such as getter/setter methods or main action methods.
class User {
public $username = "JohnDoe";
public function getUsername() {
return $this->username;
}
}
$user = new User();
echo $user->username; // Works: accessed from outside the classProtected Visibility
The protected modifier restricts access to the defining
class and its descendants.
- Scope: Protected properties and methods can only be accessed within the class itself and by classes that inherit from it (child classes/subclasses). They cannot be accessed by external code or instances of the class directly.
- Use Case: Use
protectedwhen you want to hide internal implementation details from the outside world but still allow child classes to customize or extend the behavior.
class ParentClass {
protected $apiKey = "secret_123";
}
class ChildClass extends ParentClass {
public function showKey() {
return $this->apiKey; // Works: child class can access protected parent property
}
}
$child = new ChildClass();
// echo $child->apiKey; // Error: Cannot access protected property
echo $child->showKey(); // WorksPrivate Visibility
The private modifier is the most restrictive access
level.
- Scope: Private properties and methods can only be accessed within the specific class that defines them. Neither external code nor inheriting child classes can access private members.
- Use Case: Use
privatefor sensitive data, internal helper methods, or state variables that should never be altered or relied upon by subclasses, ensuring strict encapsulation.
class Database {
private $connectionString = "mysql://host";
private function connect() {
// Internal connection logic
}
}
class MySQLDatabase extends Database {
public function testConnection() {
// return $this->connectionString; // Error: Cannot access private property of parent
}
}Quick Reference Summary
| Modifier | Access from inside the same class? | Access from inheriting child classes? | Access from outside the class? |
|---|---|---|---|
public |
Yes | Yes | Yes |
protected |
Yes | Yes | No |
private |
Yes | No | No |